s1 = json.dumps(json1)
d2 = json.loads(s1)
I am getting data in this format.
[{'creati_id': 123, 'creativ_id': 234, 'status': 'adsc', 'name': 'seded', 'email': None, 'brand': 'adc', 'market': 'dcassca', 'channel': 'dAD', 'company': 'ODASDASD', 'asset_type': 'image', 'spend': 234524234234, 'currency': 'USD', 'date_captured': 'safdasfsdfsdf', 'creative_link': 'ADADASDASD', 'post_link': None, 'ad_id': 'ASDASD', 'cta': 'DSADD', 'aspect_ratio': '1:1', 'dimensions': 'ASAD', 'width': 12123, 'height': 232342345, 'video_length': None, 'ad_account_name': 'adasdsadasd', 'ad_account_id': 'dadad', 'campaign_name': 'daDSDASDASD', 'campaign_id': 'DADASDASD', 'campaign_objective': 'ASDASDASD', 'clicks': 4303434, 'impressions': 6163824324324, 'ctr': 0.00733, 'cpm': 7.1872434, 'cpc': 1.0313233, 'video_3_sec_views': 0, 'video_15_sec_views': 0, 'video_30_sec_views': 0, 'video_25_views': None, 'video_50_views': None, 'video_75_views': None, 'video_100_views': None, 'estimated': None, 'creative1': 1.0, 'creative': 'Excellent', 'value': 1.023424324}]}
How can i save this data in CSV
CodePudding user response:
This can easily be achieved with the csv module:
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())
CodePudding user response:
You can use the standard csv
library in Python to write CSV files. From your question, I'm assuming that you have multiple rows, each having the structure you shared. If that's the case, then something like this should do the trick:
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