Doug Doug - 5 months ago 26
Python Question

Reading a JSON file using Python

I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face.

I have a json file called strings.json like this:

"strings": [ {"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ..., {"-name": "address", "#text": "Address"} ]


I want to read the json file, just that for now. I have these statements which I found out, but it's not working:

import json
from pprint import pprint

with open('strings.json') as json_data:
d = json.loads(json_data)
json_data.close()
pprint(d)


The error spitted on the console was this:

Traceback (most recent call last):
File "/home/tegris/Downloads/i18n_fieldlink/i18n_fieldlink/android/values/manipulate_json.py", line 5, in <module>
d = json.loads(json_data)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
[Finished in 0.1s with exit code 1]


EDITED

Changed from json.loads to json.load

and got this:

Traceback (most recent call last):
File "/home/tegris/Downloads/i18n_fieldlink/i18n_fieldlink/android/values/manipulate_json.py", line 5, in <module>
d = json.load(json_data)
File "/usr/lib/python2.7/json/__init__.py", line 278, in load
**kw)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 369, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 829 column 1 - line 829 column 2 (char 18476 - 18477)
[Finished in 0.1s with exit code 1]

Answer

You are using the json.loads method. More documentation here. This method is used for string arguments only. Luckily, there is a similarly named json.load method documented here. This one can be used directly on a file object.

Edit: The new message is a totally different problem. In that case, there is some invalid json in that file. For that, I would recommend running the file through a json validator.