我在文件中有这个 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 并提取其值?
网友回答:
你应该看起来像这样: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 及更高版本,因为它取决于 -语句。在Python 2.5中使用,在Python <= 2.4中,参见Justin Peel的答案,这个答案是基于这个答案。with
from __future__ import with_statement
现在,您还可以访问如下所示的单个值:
data["maps"][0]["id"] # will return 'blabla'
data["masks"]["id"] # will return 'valore'
data["om_points"] # will return 'value'
网友回答:
您的数据不是有效的 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 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_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
模板简介:该模板名称为【如何解析 JSON 并提取其值?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。