pycharm 无法将API调用数据导出到CSV

iyfjxgzm  于 2022-11-08  发布在  PyCharm
关注(0)|答案(2)|浏览(186)

我尝试使用下面的代码将从API调用接收到的json导出到csv,但收到错误消息:

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)

错误消息:
回溯(最近的呼叫排在最后):文件“/用户/xxx/PycharmProjects/api_request/export_csv_Test02.py”,第16行,在写入器中。写入行(行)文件“/库/框架/Python.框架/版本/3.10/lib/python3.10/csv.py”,第154行,在写入行中返回自。写入器。写入行(自。dict_to_list(行))文件“/库/框架/Python.框架/版本/3.10/lib/python3.10/csv.py”,第147行,属性错误:“string”对象没有属性“keys”

csbfibhn

csbfibhn1#

而不是

for row in jsonresponse:
        writer.writerow(row)

用途:

writer.writerows(jsonresponse)
xxls0lw8

xxls0lw82#

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)

相关问题