Bitcoin Murderous Maniac
Bitcoin Murderous Maniac

Reputation: 1478

Python KeyError if logic or try logic

I'm trying to loop through some JSON data to export to CSV and all is going well until I get to a portion of the data that I need to get certain field values where these fields do not always exist beneath "tags".

I'm getting the error of:

for alarm in tag["alarmst"]:
        KeyError: 'alarmst'

I believe from Built-in Exceptions reading that this means the key/field just does not exist.

I read in Errors and Exceptions that I can put this logic in a try statement to say, if this key does not exist, don't give me the error and do something else or move onto the next set of records beneath "tag" where "alarmst" is and just dump that (and the other fields specified) to the file.

I'm having trouble figuring out how to tell this logic to stop giving me this error and to only use the csv_file.writerow() function with all the field values if only the "alarmst" exist.

Since I will be working with one file and processes before this Python process runs will get the "devs" and the "tags" to their own CSV files, I cannot parse the data and cut down on the for loops within the other for loops.

I'm not sure if the issue with the if tag["alarmst"] in tag: is due to there being so many for loops within others, or if I need to use a try statement somehow instead, or if I'm just not doing something else correctly since I'm new to Python at this level of coding but it seems to work for the need thus far.

I'm running this on Windows 10 OS if that makes any difference but I assume it doesn't.

Starting Code:

import json
import csv

with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
    data = json.load(file)

with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
    csv_file = csv.writer(file)
    for dev in data["devs"]:
        for tag in dev["tags"]:
            for alarm in tag["alarmst"]:
                csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])

If Code:

import json
import csv

with open('C:\\folder\\dev\\TagAlarms.txt',"r") as file:
    data = json.load(file)

with open('C:\\folder\\dev\\TagAlarms.csv',"w",newline='') as file:
    csv_file = csv.writer(file)
    for dev in data["devs"]:
        for tag in dev["tags"]:
            for alarm in tag["alarmst"]:
                if tag["alarmst"] in tag:
                    csv_file.writerow(alarm['dateStatus'],[alarm['dateStart'], alarm['status'], alarm['type']])

Upvotes: 0

Views: 384

Answers (1)

Alex Hall
Alex Hall

Reputation: 36033

tag["alarmst"] is what throws the error. It means getting the value from tag associated with the key "alarmst" and there is no such key so it fails. if tag["alarmst"] in tag will throw the same error, and moreover you won't even reach that point if it's below for alarm in tag["alarmst"]:. What you want is:

if "alarmst" in tag:
    for alarm in tag["alarmst"]:

But much nicer is:

for alarm in tag.get("alarmst", []):

get is similar to usual square bracket access but the second argument is a default if the key is not found. So if "alarmst" is not in the dictionary this will essentially be:

for alarm in []:

which is just an empty loop that won't run at all.

Upvotes: 6

Related Questions