I have a file with several dictionaries. Below is just part of the file. I need to convert this into a csv file and eventually load it into a database. I am having issues converting it to csv.
{"transaction_type": "new", "policynum": 4994949}
{"transaction_type": "renewal", "policynum": 3848848}
{"transaction_type": "cancel", "policynum": 49494949, "cancel_table":
[{"cancel_cd": "AU", "cancel_type": "online"}, {"cancel_cd": "AA", "cancel_type": "online"}]}
I have tried to implement the below code but the cancel table key is not parsed in to the csv file properly.
import ast
import csv
with open('***\\Python\\test', 'r') as in_f, open('***\\Python\\test.csv', 'w') as out_f:
data = in_f.readlines()
writer = csv.DictWriter(out_f, fieldnames=['transaction_type', 'policynum', 'cancel_table'], extrasaction='ignore')
writer.writeheader() # For writing header
for row in data:
dict_row = ast.literal_eval(row) # because row has a dict string
writer.writerow(dict_row)
Below is the result I am getting with cancel table key not parsed in to the csv file properly. I need help getting cancel_type and different cancel_cd's as separate columns. Or cancel_cd's concatenated in one column with comma delimiter (just a thought). Sorry if it's a loaded question.
transaction_type,policynum,cancel_table
new,4994949,
old,3848848,
cancel,49494949,"[{'cancel_type': 'online','cancel_cd': 'OL'}, 'cancel_type': 'Online','cancel_cd': 'BR'},{'cancel_type': 'online','cancel_cd': 'AU', }]"