为什么Python不能解析这些JSON数据?

我在一个文件中有这个JSON:

{"maps": [{"id": "blabla","iscategorical": "0"},{"id": "blabla","iscategorical": "0"}],"masks": ["id": "valore"],"om_points": "value","parameters": ["id": "valore"]}

我写了这个脚本来打印所有的JSON数据:

import jsonfrom 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 loadsreturn _default_decoder.decode(s)File "/usr/lib/python3.5/json/decoder.py", line 339, in decodeobj, end = self.raw_decode(s, idx=_w(s, 0).end())File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decodeobj, end = self.scan_once(s, idx)json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)

如何解析JSON并提取其值?

2691578 次浏览

您的数据不是有效的JSON格式。当"masks""parameters"元素应该有{}时,您有[]

  • []用于JSON数组,在Python中称为list
  • {}用于JSON对象,在Python中称为dict

以下是您的JSON文件的外观:

{"maps": [{"id": "blabla","iscategorical": "0"},{"id": "blabla","iscategorical": "0"}],"masks": {"id": "valore"},"om_points": "value","parameters": {"id": "valore"}}

然后你可以使用你的代码:

import jsonfrom 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 jsonfrom pprint import pprint
with open('data.json') as data_file:data = json.load(data_file)pprint(data)

请注意,这仅适用于Python 2.6及更高版本,因为它取决于#0-语句。在Python 2.5中使用from __future__ import with_statement,在Python<=2.4中,请参阅贾斯汀·皮尔的回答,此答案基于此。

你现在也可以像这样访问单个值:

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 jsonfrom pprint import pprintwith open('data.json') as data_file:data_item = json.load(data_file)pprint(data_item)

print(data_item['parameters'][0]['id'])的预期输出:

{'maps': [{'id': 'blabla', 'iscategorical': '0'},{'id': 'blabla', 'iscategorical': '0'}],'masks': [{'id': 'valore'}],'om_points': 'value','parameters': [{'id': 'valore'}]}

print(data_item['parameters'][0]['id'])的预期输出:

valore