How To Parse A Json List Of Dictionaries To Csv
I have a json object retrieved from the google places api. The object is a dictionary with three keys {'status', 'html_attributions', 'results'}. The key results contain a list of
Solution 1:
This seems to work:
fields = 'lat', 'lng'withopen('test3.csv', 'wb') as csvfile:
w = csv.writer(csvfile)
w.writerow(fields) # optional -- header row
w.writerows(operator.itemgetter(*fields)(result['geometry']['location'])
for result in d['results'])
Contents oftest3.csv
file produced:
lat,lng
52.164737,9.964918
52.380744,9.861758
52.412797,9.734524
Solution 2:
So I got another way to work around this. This is the code:
##remember that d is the dictionary that has the key 'results', which is also a list of dictionaries
g=d['results']
z=[d['geometry']['location'] for d in g]
keys=['lat','lng']
with open('C:/Users/J/Desktop/test4.csv', 'wb') as csvfile:
dict_writer = csv.DictWriter(csvfile, keys)
dict_writer.writer.writerow(keys)
dict_writer.writerows(z)
Post a Comment for "How To Parse A Json List Of Dictionaries To Csv"