Angel
Angel

Reputation: 49

how to open json file in python

I am stuck here again... I have a file named "data.json" and I want to open it with python but I am getting errors.

import json
>>> data=json.load(open("data.json"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\Angel\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Angel\AppData\Local\Programs\Python\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 4912995)
>>>

Upvotes: 0

Views: 412

Answers (2)

Muzzamil
Muzzamil

Reputation: 2881

In case 2 or more than 2 record, you have to reformat your file as mentioned below OR you have to load file record by record.

You need to reformat your json to contain an array like below:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

Upvotes: 0

Jackob King
Jackob King

Reputation: 33

According to Python JSON documentation

If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.

Not knowing the content of your file, it is hard to say what is wrong, but I would suspect that text in your file is not a valid JSON object, or more likely (according to "Extra data" search, answered here) the file "data.json" includes more than one JSON object.

For example, using your code: This file works correctly

{ "name":"John", "age":30, "car":null }

but this one

{ "name":"John", "age":30, "car":null }
{ "name":"John", "age":30, "car":null }

throws the same errors

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", 
line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", 
line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", 
line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 6 column 1 (char 55)

Upvotes: 2

Related Questions