所以我从 API 中提取数据,并且只想保存来自 JSON 响应的特定指令和列表。问题是,当我将数据转储到循环中时,它会在文件中创建看起来非常奇怪的数据,而实际上这并不是 JSON。
r=requests.get(url,headers=header)
result=r.json()
with open ('myfile.json','a+') as file:
for log in result['logs']:
hello=json.dump(log['log']['driver']['username'], file)
hello=json.dump(log['log']['driver']['first_name'],file)
hello=json.dump(log['log']['driver']['last_name'],file)
for event in log['log']['events']:
hello=json.dump(event['event']['id'],file)
hello=json.dump(event['event']['start_time'],file)
hello=json.dump(event['event']['type'],file)
hello=json.dump(event['event']['location'],file)
此处的最终目标是将此数据转换为 CSV。我将它保存到 JSON 文件的唯一原因是我可以加载它并将其保存到 CSV 文件中。我的目标 API 端点是日志:
请您参考如下方法:
我认为就创建有效的 JSON 输出而言,@GBrandt 的想法是正确的,但正如我在评论中所说,我认为 JSON 到 JSON 的转换步骤并不是真正必要的——因为您可以创建来自您已有的 JSON 的 CSV 文件:
(根据您的后续问题修改为还将 start_time 拆分为两个单独的字段。)
result = r.json()
with open('myfile.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
for log in result['logs']:
username = log['log']['driver']['username']
first_name = log['log']['driver']['first_name']
last_name = log['log']['driver']['last_name']
for event in log['log']['events']:
id = event['event']['id']
start_time = event['event']['start_time']
date, time = start_time.split('T') # Split time into two fields.
_type = event['event']['type'] # Avoid using name of built-in.
location = event['event']['location']
if not location:
location = "N/A"
writer.writerow(
(username, first_name, last_name, id, date, time, _type, location))
