简体   繁体   中英

writing json string to xls file using python pandas

I am trying to parse one json string to excel file. But facing some errors

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

Error:

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

can some one help please

pd.read_json() takes a file path or a JSON string as input. You should check the type of df_json because json.loads() deserializes the input. If it is a dict you could simply do

df = pd.DataFrame(df_json)

If it's a list it's a bit more complex.

Also I would refrain from prefixing variable names "df" if they aren't dataframes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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