I'm trying to convert an API response from JSON to CSV using writerows. However it doesn't appear to be grabbing the values, I suspect it's due to DictWriter not looking into the nest to grab my value pairs, or it not knowing what key value pairs to grab.
I'm looking to extract fields 1-5 and their values to a CSV.
However when I feed the API response (as json_response) I am returned the following error, which I am unsure why passing a Dict to writerows results in an error about it being a string.
File "python-DWS.py", line 116, in <module>
JSON_to_CSV()
File "python-DWS.py", line 101, in JSON_to_CSV
w.writerows(json_response)
File "/usr/lib/python3.8/csv.py", line 157, in writerows
return self.writer.writerows(map(self._dict_to_list, rowdicts))
File "/usr/lib/python3.8/csv.py", line 151, in <genexpr>
return (rowdict.get(key, self.restval) for key in self.fieldnames)
AttributeError: 'str' object has no attribute 'get'
json_response is the API response that is a Dictionary formatted like so, however I can't print the entries nest into my CSV:
{'balance': 174, 'entries': [{'id': '20232864065', 'field1': 'email@mail.com', 'field2': '', 'field3': '', 'field4': 'oifasfasfasf', 'field5': '', 'field6': '', 'field7': '', 'field8': ''
, 'field9': '', 'field10': 'player'}, }], 'success': True, 'took': '3µs', 'total': 1}
Potion of script that takes above response and tries to convert to CSV:
##Converting Response to CSV
def JSON_to_CSV():
#Get Date for CSV Name
d = today.strftime("%d-%m-%Y")
values = [ 'field1', 'field2', 'field3', 'field4', 'field5', 'field6', 'field7' ]
#Turning JSON to CSV
with open(customername + '-' + d + '.csv', 'w') as f:
w = csv.DictWriter(f, fieldnames=values, extrasaction='ignore', delimiter=",")
w.writeheader()
print(json_response['entries'][0]['field1']) #prints first field for testing
w.writerows(json_response)