import json import csv with open('/local/dummy.json') as f: json_data = json.load(f, strict=False) with open('/local/application.csv', 'w') as outfile: csv_write = csv.writer(outfile) csv_write.writerow(["id", "SID", "Type", "ttt"]) for x in json_data["dummy"]: try: row = x["id"], x["salary"][0]["SID"], x["ttt111"][0]["ttt"], x["ttt111"][0]["S"] except KeyError: # skip this row? # using a default fill value? continue # continue with next iteration, won't write the row csv_write.writerow(row)Don't ask for permission, ask for forgiveness.
The try-except block handles the error. You can decide what you want to do, if the key does not exist.
Instead of re-opening the csv-file the whole time for only one row is inefficient.
Use the file-object outfile in the with-block instead. As long the for-loop is inside the with-block,
the file is still open and it would write.
By the way, why are you setting the default encoding?
A reload of sys direct after importing it, does not change anything.
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!