为什么Python无法解析这个JSON数据?

2024-04-27 02:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我把这个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并提取其值?


Tags: inpyidjsondatalibusrline
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 = json.load(data_file)
pprint(data)

注意,这只适用于Python2.6及更高版本,因为它取决于^{}-statement。在Python2.5中使用from __future__ import with_statement,在Python<;=2.4中,请参见Justin Peel's answer,这个答案是基于此。

您现在还可以访问如下单个值:

data["maps"][0]["id"]  # will return 'blabla'
data["masks"]["id"]    # will return 'valore'
data["om_points"]      # will return 'value'

Justin Peel's answer确实很有帮助,但是如果您使用Python 3读取JSON,应该这样做:

with open('data.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())

注意:使用json.loads而不是json.load。在Python 3中,json.loads接受一个字符串参数。json.load接受类似文件的对象参数。data_file.read()返回字符串对象。

老实说,大多数情况下,将所有json数据加载到内存中并不是问题。

数据不是有效的JSON格式。你有[]当你应该有{}时:

  • []用于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"]

试试看是否有意义。

相关问题 更多 >