Nov-27-2019, 11:56 AM
This:
Choose next time real data and this garbage, where no one knows what is what.
I tested this on windows. I put the files in a different path.
import json import csv from pathlib import Path DESKTOP = Path.home() / "Desktop" with open(DESKTOP / "my_data.json") as fd: json_data = json.load(fd) # print(list(json_data['a'][0])) with open(DESKTOP / "a.csv", "w") as outfile: writer = csv.writer(outfile, quoting=csv.QUOTE_ALL) header = ["id", "xx"] print("Writing header:", header) writer.writerow(header) for json_d in json_data["a"]: row_array = [] row_array.append(json_d.get("id") or "NO ID") try: row_array.append(json_d["LL"][0]["xx"]) except (KeyError, TypeError): row_array.append("NO XX") print("Writing row", row_array) writer.writerow(row_array) #with open(DESKTOP / "a.csv", "rb") as outfile: # print(outfile.read())Should parse this:
{ "a": [{ "id": 1, "name": "Auto", "architecture": { "axe": [ "j", "y", "r", "t", "x" ], "p": [ "Vir", "M" ] }, "LL": [{ "id": 10, "name": "A", "xx": "D", "bb": "aa", "yy": "S" }] }] }I get some unexpected \r, but don't have time to investigate.
Choose next time real data and this garbage, where no one knows what is what.
I tested this on windows. I put the files in a different path.
Output:Writing header: ['id', 'xx']
Writing row [1, 'D']
File content:Output:"id","xx"
"1","D"
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!