Python 将REST API返回的响应转换为CSV
我正在尝试将RESTAPI返回的响应写入csv文件。由于有多个请求,我正在逐个调用请求上的API。因此,会有多种反应。我无法实现所需的格式 所需格式: 代码:Python 将REST API返回的响应转换为CSV,python,json,csv,Python,Json,Csv,我正在尝试将RESTAPI返回的响应写入csv文件。由于有多个请求,我正在逐个调用请求上的API。因此,会有多种反应。我无法实现所需的格式 所需格式: 代码: import requests url ='https://reqres.in/api/users' data =[{ "name": "morpheus", "job": "leader" }, {"name":"Mark", "job":"SSE"}, {"name":"Taylor",
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]))
假设您从服务器获取的数据具有您要查找的确切密钥,类似这样的方法应该可以工作:
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')
Python内置了对csv读写的支持,允许您使用不同的分隔符和转义逻辑定义方言 包含分隔符、换行符或转义符的单元格值需要转义,否则生成的csv将被破坏-csv模块将为您执行此操作。您可以选择不同的格式(excel在加载csv时可能很挑剔),也可以定义自己的格式
您正在编写csv:首先写出响应的标题,一次,然后写出没有标题的数据。如果您可以导入外部包,pandas有一个很好的构造函数,它将从json记录创建一个表,然后是一个很好的方法来编写csv文件。如果每次都严格格式化json数据,则需要编写两行代码。感谢您的回复。我已将+“\n”添加到标题和记录中的拆分行中。如果值包含您选择的分隔符,则如何转义?这将破坏您的csv。使用内置的python csv编写器。
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')