kelua
kelua

Reputation: 283

Opening a JSON file in python

This is the first time I try to use a JSON file in Python and although I have read a lot of stuff regarding this matter, I am still very confused. I want to read a file named jason.json line by line, store it to a list named data and then print it. However, i always get the following error :

Traceback (most recent call last):
  File "try.py", line 6, in <module>
    data.append(json.loads(line))
  File "C:\Users\...\Python35\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Users\...\Python35\lib\json\__init__.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\...\Python35\lib\json\__init__.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
  json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2)

This is my code:

import json
data = []
with open('jason.json') as f:
    for line in f:
        data.append(json.loads(line))

print(data)

And this is jason.json:

{
  "E(2,3)" : "A common Afro-Cuban drum pattern",
  "E(2,5)" : "A rhythm found in Greece",
  "E(3,4)" : "It is the archetypal pattern of the Cumbia from Colombia",
  "E(3,5)" : "Persian rhythm"
}

Thank you in advance!

Upvotes: 4

Views: 15736

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124548

You are reading your file line by line, but a single line from your file is not a valid JSON document:

>>> import json
>>> json.loads('{\n')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.5/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2)

Decode the whole file in one go; this is easiest done with the json.load() function:

with open('jason.json') as f:
    data.append(json.load(f))

Upvotes: 4

aldanor
aldanor

Reputation: 3481

Note that the data stored in jason.json is a dict and not a list. So, if you want a list of tuples, you can do something like

with open('jason.json') as f:
    data = list(json.load(f).items())
print(data)

which yields

[('E(3,5)', 'Persian rhythm'), ('E(3,4)', 'It is the archetypal pattern of the Cumbia from Colombia'), ('E(2,3)', 'A common Afro-Cuban drum pattern'), ('E(2,5)', 'A rhythm found in Greece')]

Upvotes: 7

Related Questions