Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k views
in Technique[技术] by (71.8m points)

python - Can't parse json file: json.decoder.JSONDecodeError: Extra data.

I have a json file. A simplified version of it looks as following:

{
  "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
}

I run this script parser.py to parse it:

import json
from pprint import pprint

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

But I'm getting this error:

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)

Can you please point to me what's missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you already found out: that is not valid JSON.
You have to modify it to make it valid, specifically, you have to wrap your top-level objects in an array. Try this:

import json
from pprint import pprint

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

    print(data)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...