[英]Reading JSON file with Python 3
我在 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)
我得到了這個例外:
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)
我可以在 Javascript 上完美地讀取這個確切的文件,但我無法讓 Python 解析它。 我的文件有問題還是 Python 解析器有問題?
嘗試這個
import json
with open('filename.txt', 'r') as f:
array = json.load(f)
print (array)
在再次閱讀文檔的基礎上,您似乎需要將第三行更改為
json_data = json.loads(text)
或刪除該行
text = json_file.read()
因為read()
導致文件的索引到達文件的末尾。 (我想,或者,您可以重置文件的索引)。
對於 python3,只有以下對我有用 - 以上都不是。
導入json
使用 open('/emp.json', 'r') 作為 f:
data=f.read()
打印(數據)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.