繁体   English   中英

使用Python读取JSON数据-初学者问题

[英]Using Python to read json data - Beginner question

我是Json的初学者,并尝试从此处读取Automotive 5核心Json文件: http : //jmcauley.ucsd.edu/data/amazon/ ,使用以下代码

Python代码:

import json
with open('Automotive_5.json') as f:
data = json.load(f)

我不断收到JSONDecodeError: Extra data

完整的追溯:

runfile('C:/Users/Paul/Google Drive/erg2.py', wdir='C:/Users/Paul/Google Drive')
Traceback (most recent call last):

  File "<ipython-input-122-72136ec568c5>", line 1, in <module>
    runfile('C:/Users/Paul/Google Drive/erg2.py', wdir='C:/Users/Paul/Google Drive')

  File "C:\Users\Paul\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
    execfile(filename, namespace)

  File "C:\Users\Paul\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Paul/Google Drive/erg2.py", line 10, in <module>
    data = json.load(f)

  File "C:\Users\Paul\Anaconda3\lib\json\__init__.py", line 296, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

  File "C:\Users\Paul\Anaconda3\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)

  File "C:\Users\Paul\Anaconda3\lib\json\decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)

JSONDecodeError: Extra data

我下载了您的文件,并在自己的系统上进行了测试。 我不确定为什么,但是您需要分别加载每一行。 希望其他人可以提供原因,但是这段代码似乎对我有用。 也许它太大了? 我的编辑抱怨尺寸过大。

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

以JSON格式读取文件中的每一行并将其附加到数据中,而不是尝试一次全部加载。 对我来说运行没有错误。

似乎是json文件本身的问题,即您必须逐行读取数据,json文件中的所有数据都应在一个对象中,但json文件中有单独的单独对象。

如果要一次性读取数据,则将json文件的所有对象放在一个用逗号分隔的对象中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM