I am trying here to use json_normalize to somehow format the output of an API, but I keep getting a faulty and empty csv file. I tried to change df2 = pd.json_normalize(response, record_path=['LIST'])
, but keep getting this error message:
TypeError: byte indices must be integers or slices, not str
Could you please guide me on what am I doing wrong ?
Thanks a lot !
import requests
import json
import pandas as pd
url = "https://*hidden*Results/"
payload = json.dumps({
"id": 12345
})
headers = {
'Authorization': 'Basic *hidden*',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
df1 = pd.DataFrame(response).iloc[:,:-2]
df2 = pd.json_normalize(response, record_path=None)
df = pd.concat([df1, df2], axis=1)
df.to_csv("test.csv", index=False)
You are passing the variable
response
in the call:df2 = pd.json_normalize(response, record_path=None)
Which is an a
requests.models.Response
Object and you need to pass adict
, so you need to do something likepd.json_normalize(response.json(), record_path=['LIST'])
I tried it with this example and works:
EDIT I will try to do this: