I am trying to load a json file in python. My json file looks like this:
{'awesomeness': 2.5, 'party': 'Republican', 'Age': 50, 'State': 'California', 'Ideology': 0.5,
'time': {'day': 20, 'mon': 2, 'sec': 3}, 'overall': 9.5, 'review': 'Best Senator ever\tPretty balanced
view.\tNot sure if he can get reelected'}
{'awesomeness': 0.5, 'party': 'Republican', 'Age': 70, 'State': 'New York', 'Ideology': 0.8,
'time': {'day': 25, 'mon': 8, 'sec': 31}, 'overall': 5.5, 'review': 'NA'}
This is my code.
with open("senator.json") as json_file:
data = json.load(json_file)
But I got following error,
File "<stdin>", line 1, in <module>
File "<string>", line 2, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 290, in load
**kw)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
Why do I get this error and how can I load this file? Thanks for any help!
Your JSON is illegal, as the other folks already pointed out. This is why the Python JSON parser if falling flat out. Your JSON should look like this:
[
{
"awesomeness": 2.5,
"party": "Republican",
"Age": 50,
"State": "California",
"Ideology": 0.5,
"time": {
"day": 20,
"mon": 2,
"sec": 3
},
"overall": 9.5,
"review": "Best Senator ever \t Pretty balanced view. \t Not sure if he can get reelected"
},
{
"awesomeness": 0.5,
"party": "Republican",
"Age": 70,
"State": "NewYork",
"Ideology": 0.8,
"time": {
"day": 25,
"mon": 8,
"sec": 31
},
"overall": 5.5,
"review": "NA"
}
]
Notice the double quotes for strings instead of single quotes (which are illegal to denote a string inside JSON) and wrapping your two objects {...}
in square brackets so they are inside of an array
.
The latter is needed because JSON is hierarchical. Your posted JSON code simply has two objects side-by-side without any outer structure. In that case, if you thus leave the square brackets off (no array), then the JSON parser will suddenly encounter a comma ,
after your first object when it in fact expected an EOF
.
Now if you try to run your code again:
with open('senator.json', 'r') as json_file:
data = json.load(json_file)
You should be able to read out the file without any errors.
JSON strings are delimited by double quotes, not single. Your input isn't true JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With