将REST API返回的响应转换为CSV

时间:2018-10-12 12:12:14

标签: python json csv

我正在尝试将REST API返回的响应写入到csv文件中。由于有多个请求,因此我要一一调用这些请求的API。因此,将有多个响应。我无法获得所需的格式。

所需格式:

name,job,id,createdAt
morpheus,leader,727,2018-10-12T12:04:39.234Z
Mark,SSE,925,2018-10-12T12:04:40.200Z
Taylor,SE,247,2018-10-12T12:04:41.115Z

代码:

import requests

url ='https://reqres.in/api/users'
data =[{
    "name": "morpheus",
    "job": "leader"
},
    {"name":"Mark",
    "job":"SSE"},

    {"name":"Taylor",
    "job":"SE"}
]

with open('response.csv','w') as f:
    for element in data:
        r=requests.post(url,json=element)
        response = json.loads(r.text)
        for key in response.keys():
            #f.write("%s,%s"%(key,response[key]))

2 个答案:

答案 0 :(得分:0)

Python内置了对csv读写的支持,可让您定义具有不同分隔符和转义逻辑的方言。

包含分隔符或换行符或您的转义字符的单元格值需要转义,或者生成的csv被破坏-csv模块为您执行此操作。您可以选择不同的格式(加载csv时excel可能会很挑剔),也可以定义自己的格式。

https://docs.python.org/3/library/csv.html#csv.writer

答案 1 :(得分:-1)

假设您从服务器获取的数据具有您要查找的确切密钥,则应该可以执行以下操作:

data = [] # Your data here.
url = 'https://reqres.in/api/users'

desired_columns = ['name', 'job', 'id', 'createdAt']
with open('response.csv', 'w') as f:

    # First we need to write the column names to the file
    f.write(','.join(desired_columns) + '\n')

    for element in data:
        r = requests.post(url, json=element)

        response = json.loads(r.text)

        # Here, I will assume response has 'name', 'job', 'id' and 'createdAt'
        # as keys to the dictionary. We will save them to the list 'data_to_write'
        # And then write that out the same way we did above.
        data_to_write = []
        for column in desired_columns:
            data_to_write.append(response[column])

        f.write(','.join(data_to_write) + '\n')