如何将JSON文件读取为pandas DataFrame?

31
我正在使用Python 3.6,并尝试使用以下代码将JSON文件(350 MB)下载为Pandas数据框。然而,我遇到了以下错误:
data_json_str = "[" + ",".join(data) + "]
"TypeError: sequence item 0: expected str instance, bytes found
怎么修复这个错误?
import pandas as pd

# read the entire file into a python array
with open('C:/Users/Alberto/nutrients.json', 'rb') as f:
   data = f.readlines()

# remove the trailing "\n" from each line
data = map(lambda x: x.rstrip(), data)

# each element of 'data' is an individual JSON object.
# i want to convert it into an *array* of JSON objects
# which, in and of itself, is one large JSON object
# basically... add square brackets to the beginning
# and end, and have all the individual business JSON objects
# separated by a comma
data_json_str = "[" + ",".join(data) + "]"

# now, load it into pandas
data_df = pd.read_json(data_json_str)
6个回答

54

从您的代码来看,似乎您正在加载一个每行都有JSON数据的JSON文件。 read_json 支持一个lines参数来处理这种数据:

data_df = pd.read_json('C:/Users/Alberto/nutrients.json', lines=True)

注意
如果你只有单个JSON对象而不是每行一个JSON对象,请删除lines=True


12
使用json模块,您可以将json解析为Python对象,然后从中创建一个数据框:
import json
import pandas as pd
with open('C:/Users/Alberto/nutrients.json', 'r') as f:
    data = json.load(f)
df = pd.DataFrame(data)

1
我使用了上述代码,并出现了“JSONDecodeError: Extra data: line 2 column 1 (char 110)”的错误。 - Biranchi
在我的情况下不需要 'r',但也不会有影响(未经测试,只是从经验中得出的结论)。 - questionto42

8
如果以二进制形式打开文件('rb'),则会得到字节。如下所示:
with open('C:/Users/Alberto/nutrients.json', 'rU') as f:

还有一个注意点,正如这篇回答中所提到的,你也可以直接使用pandas,例如:

df = pd.read_json('C:/Users/Alberto/nutrients.json', lines=True)

1
使用pandas读取json文件的最简单方法是:
pd.read_json("sample.json",lines=True,orient='columns')

处理嵌套的json,如下所示

[[{Value1:1},{value2:2}],[{value3:3},{value4:4}],.....]

使用Python基础知识。
value1 = df['column_name'][0][0].get(Value1)

1
这里的Value1是什么?是列的名称吗? - Kubra Altun
@Kubra Value1 是键,相应的值将被返回。 - Yashraj Nigam

1
如果你想将其转换为一个JSON对象的数组,我认为这个会做你想要的。
import json
data = []
with open('nutrients.json', errors='ignore') as f:
    for line in f:
        data.append(json.loads(line))
print(data[0])

0
请看下面的代码。
#call the pandas library
import pandas as pd
#set the file location as URL or filepath of the json file
url = 'https://www.something.com/data.json'
#load the json data from the file to a pandas dataframe
df = pd.read_json(url, orient='columns')
#display the top 10 rows from the dataframe (this is to test only)
df.head(10)
请查看代码并根据您的需求进行修改。我已添加注释以解释每行代码。希望这可以帮到您!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,