简体   繁体   中英

Cannot Export API call data to CSV

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'

Instead of

for row in jsonresponse:
        writer.writerow(row)

Use:

writer.writerows(jsonresponse)
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)

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