使用Python 3读取JSON文件

And*_*res 19 python parsing json

我在Windows 10 x64上使用Python 3.5.2.在JSON我读文件是是一种JSON含有2个以上阵列阵列.

我正在尝试JSON使用该json模块解析此文件.如文档中所述,JSON文件必须符合RFC 7159.我在这里检查了我的文件,它告诉我RFC 7159格式完全没问题,但是在尝试使用这个简单的python代码读取它时:

with open(absolute_json_file_path, encoding='utf-8-sig') as json_file:
    text = json_file.read()
    json_data = json.load(json_file)
    print(json_data)
Run Code Online (Sandbox Code Playgroud)

我得到了这个例外:

Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm 4.0.5\helpers\pydev\pydevd.py", line 2217, in <module>
    globals = debugger.run(setup['file'], None, None)
  File "C:\Program Files (x86)\JetBrains\PyCharm 4.0.5\helpers\pydev\pydevd.py", line 1643, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files (x86)\JetBrains\PyCharm 4.0.5\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc) 
  File "C:/Users/Andres Torti/Git-Repos/MCF/Sur3D.App/shapes-json-checker.py", line 14, in <module>
    json_data = json.load(json_file)
  File "C:\Users\Andres Torti\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\Andres Torti\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Andres Torti\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Andres Torti\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Run Code Online (Sandbox Code Playgroud)

我可以在Javascript上完全正确地读取这个确切的文件,但我不能让Python解析它.我的文件有什么问题或者Python解析器有什么问题吗?

lca*_*lov 38

试试这个

import json

with open('filename.txt', 'r') as f:
    array = json.load(f)

print (array)
Run Code Online (Sandbox Code Playgroud)


Wil*_*ter 16

在再次阅读文档的基础上,您似乎需要将第三行更改为

json_data = json.loads(text)
Run Code Online (Sandbox Code Playgroud)

或删除该行

text = json_file.read()
Run Code Online (Sandbox Code Playgroud)

因为read()导致文件的索引到达文件的末尾.(我想,或者,您可以重置文件的索引).

  • 啊,我想通了;如果你先调用 `read()`,那么文件对象在文件末尾有它的索引,并且不再有任何东西可以用来制作 json。 (2认同)