python - How can I write Parsed JSON to a CSV fie? -
note: please see comments of ticked answer resolution :)
i'm writing python accesses api , exports server's response (json) csv file. json nested.
this json response server (this sample of response):
{ "id":182774, "website_id":307842, "engine_provider":"google", "engine_name":"united kingdom", "keywords":[ { "id":4464443, "groups_id":[ 44424 ], "name":"smart e70 interactive display", "positions":{ "2017-03-16":10 } }, { "id":4464442, "groups_id":[ 44424 ], "name":"smart podium sp518", "positions":{ "2017-03-16":4 } }, { "id":4464441, "groups_id":[ 44424 ], "name":"smart board m680", "positions":{ "2017-03-16":3 } }, { "id":4464338, "groups_id":[ 51168 ], "name":"nec lamps", "positions":{ "2017-03-16":4 } } ] }
if json looking wrong, it's because edited wrong when sampling post.
in python try parse query response , write nested fields csv table this:
parsedqueryresponse = queryresponse.json() f = csv.writer(open(csvoutputpath, "wb+")) f.writerow(["name", "positions", "id"]) parsedqueryresponse in parsedqueryresponse: f.writerow([parsedqueryresponse["keywords"]["name"], parsedqueryresponse["keywords"]["positions"], parsedqueryresponse["keywords"]["id"]])
when run script error:
"line 146, in f.writerow([parsedqueryresponse["keywords"]["name"], typeerror: string indices must integers"
line 146 1 (also referenced error message):
f.writerow([parsedqueryresponse["keywords"]["name"]
what doing wrong here? tried changing json fields use ' instead of " didn't seem make things better...
please try this,
import csv import json parsedqueryresponse = queryresponse.json() f = csv.writer(open(csvoutputpath, "wb+")) f.writerow(["name", "positions", "id"]) entry in parsedqueryresponse["keywords"]: f.writerow([entry["name"], entry["positions"], entry["id"]])
output:
name,positions,id smart e70 interactive display,{2017-03-16: 10},4464443 smart podium sp518,{2017-03-16: 4},4464442 smart board m680,{2017-03-16: 3},4464441 nec lamps,{2017-03-16: 4},4464338
please let me know in terns of queries.
Comments
Post a Comment