使用 python pandas 将 json 字符串写入 xls 文件

writing json string to xls file using python pandas

我正在尝试将一个 json 字符串解析为 excel 文件。但面临一些错误

import pandas
...
...
response = requests.get(BASE_URL, headers=headers)
#print(response.text)
df_json = json.loads(response.text)
print(df_json) -- this is printing json as string
df = pd.read_json(df_json)
-- now i want to load this into excel
df.to_excel('c:\scripts\DATAFILE.xls', sheet_name='Sheet1', index=False, engine='xlsxwriter')

错误:

ValueError: Invalid file path or buffer object type: <class 'dict'>

有人能帮忙吗

pd.read_json() 将文件路径或 JSON 字符串作为输入。您应该检查 df_json 的类型,因为 json.loads() 反序列化输入。 如果它是一个字典,你可以简单地做

df = pd.DataFrame(df_json)

如果它是一个列表,那就有点复杂了。

另外,如果变量名不是数据帧,我会避免在变量名前加上前缀“df”。