I'm following along with https://realpython.com/python-json/. I'm using Python 3.8, on a Windows 10 machine, using IDLE.
I deviated a bit from the example.
>>> import json >>> >>> data1 = { 'president': { 'name': 'dumb-bell beetlebox', 'species': 'betelgusian' } } >>> data2 = { 'emperor': { 'name': 'Ezekiel Wheel', 'species': 'klingon' } } >>> data3 = { 'king': { 'name': 'tech shiny', 'species': 'two hundred' } } >>> >>> with open('data1_file.json', 'w') as wf: json.dump(data1, wf) >>> with open('data1_file.json', 'a') as af: af.write('\n') json.dump(data2, af) af.write('\n') json.dump(data3, af) 1 1
This created the json file, with the data per line.
I then tried to read it.
>>> with open('data1_file.json', 'r') as rf: data = json.load(rf) Traceback (most recent call last): File "<pyshell#139>", line 2, in <module> data4 = json.load(rf) File "D:\Program Files (x86)\Python38-32\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "D:\Program Files (x86)\Python38-32\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "D:\Program Files (x86)\Python38-32\lib\json\decoder.py", line 340, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 73)
On the advice from a friend, who said there may have been extraneous data in the file -
>>> print(repr(open('data1_file.json').read())) '{"president": {"name": "dumb-bell beetlebox", "species": "betelgusian"}}\n{"emperor": {"name": "Ezekiel Wheel", "species": "klingon"}}\n{"king": {"name": "tech shiny", "species": "two hundred"}}'
Any help would be appreciated. Thank you.
https://stackoverflow.com/questions/66863757/reading-a-json-file-using-python-jsondecodeerror-extra-data March 30, 2021 at 09:48AM
没有评论:
发表评论