通过api获取数据时无法在python中将json数据转换为csv
原文标题 :Not able to convert json data into csv in python while fetching data through api
s1 = json.dumps(json1)
d2 = json.loads(s1)
我正在以这种格式获取数据。
[{‘creati_id’:123,’creativ_id’:234,’status’:’adsc’,’name’:’seded’,’email’:无,’brand’:’adc’,’market’:’dcassca ‘,’channel’: ‘dAD’,’company’: ‘ODASDASD’,’asset_type’: ‘image’,’spend’: 234524234234,’currency’: ‘USD’,’date_captured’: ‘safdasfsdfsdf’,’creative_link ‘:’ADADASDASD’,’post_link’:无,’ad_id’:’ASDASD’,’cta’:’DSADD’,’aspect_ratio’:’1:1’,’尺寸’:’ASAD’,’宽度’: 12123,’高度’:232342345,’video_length’:无,’ad_account_name’:’adasdsadasd’,’ad_account_id’:’dadad’,’campaign_name’:’daDSDASDASD’,’campaign_id’:’DADASDASD’,’campaign_objective’: ‘ASDASD’,’点击次数’:4303434,’展示次数’:6163824324324,’ctr’:0.00733,’cpm’:7.1872434,’cpc’:1.0313233,’video_3_sec_views’:0,’video_15_sec_views’:0,’video_30_sec’ 0,’video_25_views’:无,’video_50_views’:无,’video_75_views’:无,’video_100_views’:无,’估计’:无,’creative1’:1.0,’creative’:’优秀’,’value’: 1.023424324}]}
我如何将这些数据保存在 CSV 中
回复
我来回复-
Floh 评论
这可以通过 csv 模块轻松实现:
import csv data = [ { "creati_id": 123, "creativ_id": 234, "status": "adsc", "name": "seded", } ] with open("data_file.csv", "w") as data_file: csv_writer = csv.writer(data_file) header = data[0].keys() csv_writer.writerow(header) for line in data: csv_writer.writerow(line.values())
2年前 -
Dan Babington 评论
您可以使用 Python 中的标准
csv
库来编写 CSV 文件。根据您的问题,我假设您有多行,每行都有您共享的结构。如果是这样的话,那么这样的事情应该可以解决问题:import csv json1 = [ {'creati_id': 123, 'creativ_id': 234, 'status': 'adsc', 'name': 'seded', 'email': None, 'brand': 'adc', 'market': 'dcassca', 'channel': 'dAD'}, {'creati_id': 123, 'creativ_id': 234, 'status': 'adsc', 'name': 'seded', 'email': None, 'brand': 'adc', 'market': 'dcassca', 'channel': 'dAD'} ] header_names = json1[0].keys() # Extract the header names data_rows = [row.values() for row in json1] # Extract the values for each with open('output.csv', 'w', encoding='UTF8', newline='') as file: writer = csv.writer(file) writer.writerow(header_names) # Writes the header writer.writerows(data_rows) # Writes the rows
2年前