初学者问题。
我正在卷曲我的数据库以查看特定requestId
是否存在某个对象。
理想情况下,我的代码类似于:
if totalobjects_start == 0:
create a cron job
elif totalobjects_start < 24:
pass
当表中存在带有该requestId的1+对象时,这很好。请注意,该属性totalObjects
为1
。
{"offset":0,"data":[{"created":1439328152000,"locationId":0,"requestId":"A6NMD6","latency":0,"___class":"Latency","totalObjects":1}
但是,如果表中没有requestId
的对象,则JSON转储如下所示:
{"code":1017,"message":"Invalid where clause. Not existing columns: "}
我遇到的问题是为条件语句分配变量的内容。如果表中没有对象,并且我尝试将totalobjects_start
分配给JSON属性totalObjects
,我将获得KeyError
,因为它不存在于JSON转储中
这是我想要做的伪代码:
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
以下代码显然是错误的,但我想至少付出努力:
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
答案 0 :(得分:3)
通常使用in关键字来检查dict中是否存在密钥。如果您还不知道这一点 - 当您在python中加载json字符串时,它会将其转换为dict。在下面的代码中,假设响应变量实际上由db驱动程序填充。
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
答案 1 :(得分:0)
我对crontab不太了解,但你的代码部分似乎非常正确。我认为这可以帮助您解决JSON数据的问题。
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