上篇 下篇
Json Python Append List
2017年09月08日 ⁄ 问答 ⁄ 共 2643字 ⁄ 字号
I want to extract locality, postcode, and address from a json file.
And append to a csv file with column names locality, postcode, and address.
Sample json file:
{ "@graph": [ { "@id": "http://datos.madrid.es/egob/catalogo/tipo/entidadesyorganismos/6430067-bibliobus-numero-10-recorrido-semanal.json", "@type": "http://datos.madrid.es/egob/kos/entidadesYorganismos/Bibliobuses", "id": "6430067", "title": "Bibliobús número 10. Recorrido semanal", "relation": "http://www.madrid.es/sites/v/index.jsp?vgnextchannel=9e4c43db40317010VgnVCM100000dc0ca8c0RCRD&vgnextoid=734a6e6b06637310VgnVCM1000000b205a0aRCRD", "address": { "locality": "MADRID", "postal-code": "", "street-address": "Servicio itinerante " }, "organization": { "organization-desc": "", "accesibility": "0", "schedule": "Consulte en documentación asociada el detalle del Horario de verano", "services": "", "organization-name": "Bibliobús número 10. Recorrido semanal" } }, { "@id": "http://datos.madrid.es/egob/catalogo/tipo/entidadesyorganismos/6431159-bibliobus-numero-11-recorrido-semanal.json", "@type": "http://datos.madrid.es/egob/kos/entidadesYorganismos/Bibliobuses", "id": "6431159", "title": "Bibliobús número 11. Recorrido semanal", "relation": "http://www.madrid.es/sites/v/index.jsp?vgnextchannel=9e4c43db40317010VgnVCM100000dc0ca8c0RCRD&vgnextoid=1d69b5f1cea37310VgnVCM1000000b205a0aRCRD", "address": { "locality": "MADRID", "postal-code": "", "street-address": "Servicio itinerante " }, "organization": { "organization-desc": "", "accesibility": "0", "schedule": "Consulte en documentación asociada el detalle del horario de verano", "services": "", "organization-name": "Bibliobús número 11. Recorrido semanal" } ] } My Source Code import json import csv sourcefile = open('bibliobuses.json', 'r', encoding='latin-1') json_data = json.load(sourcefile) print(json_data) outputfile = open("convertedjson2.csv", "w", encoding="latin-1") outputwriter = csv.writer(outputfile) for station in json_data["@graph"]: header_row = [] for attribute in station["address"]: header_row.append(attribute) outputwriter.writerow(header_row) listado = [] for attribute in station["address"]: listado.append(station["address"]["locality"]) listado.append(station["address"]["postal-code"]) listado.append(station["address"]["street-address"]) outputwriter.writerow(listado)However, the outputwriter csv file shows the header rows repeated.
locality postal-code street-adress MADRID NA Servicio itinerante locality postal-code street-address MADRID NA Servicio itinerante locality postal-code street-address MADRID NA Servicio itinerante locality postal-code street-address MADRID NA Servicio itinerante locality postal-code street-address MADRID NA Servicio itinerante locality postal-code street-address . . . MADRID 28015 CALLE CONDE DUQUE 9 . . .How can I get one header row with their corresponding values?
Grateful for any help.
Thank you.