我在一个文件中有这个JSON:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [
"id": "valore"
],
"om_points": "value",
"parameters": [
"id": "valore"
]
}
我编写了这个脚本来打印所有JSON数据:
import json
from pprint import pprint
with open('data.json') as f:
data = json.load(f)
pprint(data)
该程序引发了一个例外:
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并提取其值?
您的数据不是有效的JSON格式。当“masks”和“parameters”元素应该具有{}时,您具有[]:
[]表示JSON数组,在Python中称为列表{}用于JSON对象,在Python中称为dict
以下是JSON文件的外观:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": {
"id": "valore"
},
"om_points": "value",
"parameters": {
"id": "valore"
}
}
然后您可以使用代码:
import json
from pprint import pprint
with open('data.json') as f:
data = json.load(f)
pprint(data)
使用数据,您现在还可以找到如下值:
data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]
试试这些,看看它是否开始有意义。
你的data.json应该是这样的:
{
"maps":[
{"id":"blabla","iscategorical":"0"},
{"id":"blabla","iscategorical":"0"}
],
"masks":
{"id":"valore"},
"om_points":"value",
"parameters":
{"id":"valore"}
}
您的代码应为:
import json
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
pprint(data)
注意,这只适用于Python 2.6及更高版本,因为它取决于with语句。在Python 2.5中,使用from __future_importwith_statement,在Python<=2.4中,请参见Justin Peel的答案,该答案基于此。
现在,您还可以访问如下单个值:
data["maps"][0]["id"] # will return 'blabla'
data["masks"]["id"] # will return 'valore'
data["om_points"] # will return 'value'
这里是修改后的data.json文件:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [{
"id": "valore"
}],
"om_points": "value",
"parameters": [{
"id": "valore"
}]
}
您可以使用以下行在控制台上调用或打印数据:
import json
from pprint import pprint
with open('data.json') as data_file:
data_item = json.load(data_file)
pprint(data_item)
打印的预期输出(data_item['parameters'][0]['id']):
{'maps': [{'id': 'blabla', 'iscategorical': '0'},
{'id': 'blabla', 'iscategorical': '0'}],
'masks': [{'id': 'valore'}],
'om_points': 'value',
'parameters': [{'id': 'valore'}]}
打印的预期输出(data_item['parameters'][0]['id']):
valore