如何用pandas读取json文件?

时间:2016-08-19 13:25:16

标签: python json list pandas scrapy

我用scrapy抓取了一个网站并将数据存储在json文件中 链接到json文件:https://drive.google.com/file/d/0B6JCr_BzSFMHLURsTGdORmlPX0E/view?usp=sharing

但是json不是标准的json并且给出了错误:

>>> import json
>>> with open("/root/code/itjuzi/itjuzi/investorinfo.json") as file:
...     data = json.load(file)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/root/anaconda2/lib/python2.7/json/__init__.py", line 291, in load
**kw)
  File "/root/anaconda2/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/root/anaconda2/lib/python2.7/json/decoder.py", line 367, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 3 column 2 - line 3697 column 2 (char 45 - 3661517)

然后我尝试了这个:

with open('/root/code/itjuzi/itjuzi/investorinfo.json','rb') as f:
     data = f.readlines()
data = map(lambda x: x.decode('unicode_escape'), data)
>>> df = pd.DataFrame(data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pd' is not defined
>>> import pandas as pd
>>> df = pd.DataFrame(data)
>>> print pd
<module 'pandas' from '/root/anaconda2/lib/python2.7/site-packages/pandas/__init__.pyc'>
>>> print df
[3697 rows x 1 columns]

为什么这只返回1列?

如何标准化json文件并正确地使用pandas读取它?

2 个答案:

答案 0 :(得分:9)

试试这个:

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

这样做的好处是可以很好地处理不适合内存的大型JSON文件

编辑: 您的数据无效JSON。 删除前3行中的以下内容,它将验证:

[{
    "website": ["\u5341\u65b9\u521b\u6295"]
}]

EDIT2 [因为您需要从json访问嵌套值]:

您现在还可以访问以下单个值:

data["one"][0]["id"]  # will return 'value'
data["two"]["id"]    # will return 'value'
data["three"]      # will return 'value'

答案 1 :(得分:1)

请尝试以下代码:(您缺少一些东西)

>>> import json
>>> with open("/root/code/itjuzi/itjuzi/investorinfo.json") as file:
 ...     data = json.load(file.read())