Home > Mobile >  Cannot Export API call data to CSV
Cannot Export API call data to CSV

Time:08-11

I am trying to export the json received from an API call to csv using the code below but getting the error messages:

import requests
import csv
import json


r='http://openapi.seoul.go.kr:8088/504949776872656935396c46496663/json/airPolutionMeasuring1Hour/1/50/'

response=requests.get(r)
output = response.text
jsonresponse=json.loads(output)
with open ('data_02.csv', 'w', newline ='') as csvfile:
    fieldnames=['DATA_DT', 'LOC_CODE', 'ITEM_CODE', 'DATA_VALUE', 'DATA_STATE', 'DATA_NOVER', 'DATA_ROVER', "REGIST_DT"]
    writer=csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for row in jsonresponse:
        writer.writerow(row)



#print(output)

The error message:

Traceback (most recent call last): File "/Users/xxx/PycharmProjects/api_request/export_csv_Test02.py", line 16, in writer.writerow(row) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/csv.py", line 154, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/csv.py", line 147, in _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'str' object has no attribute 'keys'

CodePudding user response:

Instead of

for row in jsonresponse:
        writer.writerow(row)

Use:

writer.writerows(jsonresponse)

CodePudding user response:

import requests
import csv
import json


r='http://openapi.seoul.go.kr:8088/504949776872656935396c46496663/json/airPolutionMeasuring1Hour/1/50/'

response=requests.get(r)
output = response.text
jsonresponse=json.loads(output)
with open ('data_02.csv', 'w', newline ='') as csvfile:
    fieldnames=['DATA_DT', 'LOC_CODE', 'ITEM_CODE', 'DATA_VALUE', 'DATA_STATE', 'DATA_NOVER', 'DATA_ROVER', "REGIST_DT"]
    writer=csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(jsonresponse['airPolutionMeasuring1Hour']['row'])


# print(output)
  • Related