简体   繁体   中英

Handle a KeyError while parsing JSON

Beginner question.

I am curling my database to see if an object exists by a certain requestId .

Ideally, my code would be something like:

if totalobjects_start == 0:
    create a cron job
elif totalobjects_start < 24:
    pass

This is fine when 1+ objects exist in the table with that requestId. Notice the property totalObjects is 1 .

{"offset":0,"data":[{"created":1439328152000,"locationId":0,"requestId":"A6NMD6","latency":0,"___class":"Latency","totalObjects":1}

However, when there doesn't exist an object in table with that requestId , the JSON dump looks like:

{"code":1017,"message":"Invalid where clause. Not existing columns: "}

What I am having trouble with is what to assign the variable for the conditional statement. If there is no object in the table and I try to assign totalobjects_start to the JSON property totalObjects , I will get a KeyError , since it doesn't exist in the JSON dump.

Here is the pseudocode for what I am trying to do:

try to see if code 1017
if not, see if totalObjects is at least 1

if code 1017 (no objects):
    create a cron job
elif totalObjects is at least 1 and less than 24:
    pass

The following code is obviously wrong, but I wanted to at least make an effort:

totalobjects_start_str = totalobjects_search_start.decode(encoding='utf-8')

def totalobjects_count():
    try:
        totalobjects_start_1017 = json.loads(totalobjects_start_str, strict=False)['code']
    except (ValueError, KeyError, TypeError):
        totalobjects_start = int(json.loads(totalobjects_start_str, strict=False)['totalObjects'])

totalobjects_count()

if totalobjects_start_1017 == '1017':
    job.hours.every(2)
    cron.write()
elif totalobjects_start < 24:
    pass

In general use the in keyword to check if a key is present in a dict. In case you didn't already know this - when you load a json string in python it will convert it to a dict. In the below code lets assume that the response variable is actually populated by your db driver.

import json

# Pretend the following came from the db
response = '{"code":1017,"message":"Invalid where clause. Not existing columns: "}'
data = json.loads(response)
if 'code' in data and data['code'] == 1017:
    # create the cron
elif 'totalObjects' in data and 0 < data['totalObjects'] < 24:
    # probably log this somewhere
    pass
else:
    # probably have some action for when totalObjects is 0 or >= 24
    pass

I don't have much idea about crontab but that part of your code seems quite correct. I assume that this should help you solve your problem with the JSON data.

import json

data1 = json.dumps({'a':123, 'b':456, 'requestId': 329864798}) #sample json data with 'requestId'
data2 = json.dumps({'a':123, 'b':456}) #sample json data without 'requestId'

def totalobjects_count(data):
    d = json.loads(data)
    try:
        if d['requestId']:
            return 1
    except KeyError:
        return 1017

totalobjects = totalobjects_count(data1) #use data1 and data2 alternatively to simulate both use-cases

if totalobjects == 1:
    #do something here
    pass
elif totalobjects == 1017:
    #show some error or execute alternative code
    pass
else:
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM