为什么 Python 无法解析此 JSON 数据?[关闭]
- 2024-11-25 08:50:00
- admin 原创
- 161
问题描述:
我在文件中有这个 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 并提取其值?
解决方案 1:
您的数据不是有效的JSON格式。对于和元素,[]
您应该有:{}
`"masks"`"parameters"
[]
`list`用于 JSON 数组,在 Python 中调用{}
`dict`用于 JSON 对象,在 Python 中调用
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"]
尝试一下,看看是否有意义。
解决方案 2:
你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 及更高版本,因为它取决于 -statement with
。在 Python 2.5 中使用from __future__ import with_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'
解决方案 3:
以下是修改后的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)
预期输出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
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD