无法解析json文件:json.decoder.JSONDecodeError:额外的数据。

时间:2018-08-19 16:30:34

标签: python json parsing

我有一个json文件。它的简化版本如下:

{
  "host": "a.com",
  "ip": "1.2.2.3",
  "port": 8
}
{
  "host": "b.com",
  "ip": "2.5.0.4",
  "port": 3

}
{
  "host": "c.com",
  "ip": "9.17.6.7",
  "port": 4
}

我运行以下脚本parser.py进行解析:

import json
from pprint import pprint

with open('myfile.json') as f:
    data = json.load(f)
pprint(data)

但是我遇到了这个错误:

Traceback (most recent call last):
  File "parser.py", line 5, in <module>
    data = json.load(f)
  File "/usr/lib/python3.6/json/__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 6 column 1 (char 54)

您能给我指点什么吗?

3 个答案:

答案 0 :(得分:0)

您已经发现无效的JSON。
您必须进行修改以使其有效,特别是必须将顶级对象包装在数组中。试试这个:

import json
from pprint import pprint

with open('myfile.json') as f:
    data = json.loads("[" + 
        f.read().replace("}\n{", "},\n{") + 
    "]")

    print(data)

答案 1 :(得分:0)

您的JSON数据集无效,您可以将它们合并为一个对象数组。 例如:

[
    {
        "host": "a.com",
        "ip": "1.2.2.3",
        "port": 8
    }, {
        "host": "b.com",
        "ip": "2.5.0.4",
        "port": 3

    }, {
        "host": "c.com",
        "ip": "9.17.6.7",
        "port": 4
    }
]

在JSON中,您不能有多个顶级对象,但是可以有对象数组,并且有效

You can see more JSON Data Set examples if you want in this link

答案 2 :(得分:0)

您的JSON文件格式不正确。
应该是这样,在列表内,用逗号分隔:

[
    {
     "host": "a.com",
     "ip": "1.2.2.3",
     "port": 8
    },
    {
     "host": "b.com",
     "ip": "2.5.0.4",
     "port": 3

    },
    {
     "host": "c.com",
     "ip": "9.17.6.7",
     "port": 4
    },
]