在python中打开JSON文件

时间:2016-05-14 14:53:16

标签: python json

这是我第一次尝试在Python中使用JSON文件,虽然我已经阅读了很多关于此事的内容,但我仍然很困惑。我想逐行读取一个名为jason.json的文件,将其存储到名为data的列表中,然后将其打印出来。但是,我总是得到以下错误:

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)

这是我的代码:

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

print(data)

这是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"
}

提前谢谢!

2 个答案:

答案 0 :(得分:3)

您正在逐行读取文件,但文件中的一行不是有效的JSON文档:

>>> 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)

一次解码整个文件;这是使用json.load()函数最简单的方法:

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

答案 1 :(得分:1)

请注意,jason.json中存储的数据是dict而不是列表。因此,如果您想要一个元组列表,您可以执行类似

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

产生

[('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')]