Ignore or replace 'KeyError' in 'csv_file.writerow' - Python

47 Views Asked by At

I am working on a Python script that pulls data from an API, turns it to a JSON then goes through and writes a row to a CSV file for a small database, it writes a new row for each of the devices in the JSON, for as many entries as there are in the JSON, somewhere between 10 and 100 it is running great and doing as expected until it hits a field without an entry in it. it then throws a key error.

I would like to either skip the missing field completely (while still writing the rest of the row) or replace the missing field with "N/A" or "NaN" or "No data" or something like that. i have tried a few things from here but I'm either googling the wrong thing or not finding the answer for my problem

Heres the code:


JSON_Temp.json --->   {"numFound": 5, "devices": [
{"general": {"mac": "M1033770383",}, "network": {"gateway": 542, "downRssi": -110, "upRssi": -124}, "reading": {"connectivity": "ONLINE"}}, 
{"general": {"mac": "A1007634388",}, "network": {"downRssi": -110, "upRssi": -124}, "reading": {"connectivity": "OFFLINE"}},
{"general": {"mac": "C1031474373",}, "network": {"gateway": 533, "downRssi": -110, "upRssi": -124}}]}

--------------------------------------------------------
import csv
import json

with open("CSV Builder/JSON_Temp.json") as file:
    data = json.load(file)

fname = "CSV Builder/DeviceReport.csv"
with open(fname, "w", newline="") as file:
   csv_file = csv.writer(file)
   csv_file.writerow(['MAC',
                      'Gateway',
                      'Connectivity',
                      'Down_RSSI',
                      'Up_RSSI',
                      ])

   for item in data["devices"]:
     csv_file.writerow([item['general']['mac'], 
                        item['network']['gateway'],
                        item['reading']['connectivity'],
                        item['network']['downRssi'],
                        item['network']['upRssi'],
                    ])

     print('done')


0

There are 0 best solutions below