為什么Python不能解析這個JSON數(shù)據(jù)?我在文件中有這個JSON:{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [
"id": "valore"
],
"om_points": "value",
"parameters": [
"id": "valore"
]}我寫了這個腳本來打印所有的JSON數(shù)據(jù):import jsonfrom pprint import pprintwith open('data.json') as f:
data = json.load(f)pprint(data)但該程序引發(fā)了一個例外:Traceback (most recent call last):
File "<pyshell#1>", line 5, in <module>
data = json.load(f)
File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)如何解析JSON并提取其值?
3 回答

慕尼黑的夜晚無繁華
TA貢獻(xiàn)1864條經(jīng)驗 獲得超6個贊
您的數(shù)據(jù)不是有效的JSON格式。你有[]
什么時候應(yīng)該{}
:
[]
用于JSON數(shù)組,list
在Python 中調(diào)用{}
適用dict
于在Python 中調(diào)用的JSON對象
以下是您的JSON文件的外觀:
{ "maps": [ { "id": "blabla", "iscategorical": "0" }, { "id": "blabla", "iscategorical": "0" } ], "masks": { "id": "valore" }, "om_points": "value", "parameters": { "id": "valore" }}
然后你可以使用你的代碼:
import jsonfrom pprint import pprintwith open('data.json') as f: data = json.load(f)pprint(data)
使用數(shù)據(jù),您現(xiàn)在還可以找到如下值:
data["maps"][0]["id"]data["masks"]["id"]data["om_points"]
嘗試一下,看看它是否有意義。

慕的地6264312
TA貢獻(xiàn)1817條經(jīng)驗 獲得超6個贊
你data.json
應(yīng)該看起來像這樣:
{ "maps":[ {"id":"blabla","iscategorical":"0"}, {"id":"blabla","iscategorical":"0"} ],"masks": {"id":"valore"},"om_points":"value","parameters": {"id":"valore"}}
你的代碼應(yīng)該是:
import jsonfrom pprint import pprintwith open('data.json') as data_file: data = json.load(data_file)pprint(data)
請注意,這僅適用于Python 2.6及更高版本,因為它取決于with
-statement。在Python 2.5中使用from __future__ import with_statement
,在Python <= 2.4中,請參閱Justin Peel的答案,該答案基于此答案。
您現(xiàn)在還可以訪問單個值,如下所示:
data["maps"][0]["id"] # will return 'blabla'data["masks"]["id"] # will return 'valore'data["om_points"] # will return 'value'
添加回答
舉報
0/150
提交
取消