Python 在解析JSON时处理KeyError
初学者问题 我正在卷曲数据库,查看某个Python 在解析JSON时处理KeyError,python,json,python-3.x,Python,Json,Python 3.x,初学者问题 我正在卷曲数据库,查看某个requestId是否存在对象 理想情况下,我的代码应该是: if totalobjects_start == 0: create a cron job elif totalobjects_start < 24: pass 但是,当表中不存在具有该requestId的对象时,JSON转储如下所示: {"code":1017,"message":"Invalid where clause. Not existing columns: "
requestId
是否存在对象
理想情况下,我的代码应该是:
if totalobjects_start == 0:
create a cron job
elif totalobjects_start < 24:
pass
但是,当表中不存在具有该requestId
的对象时,JSON转储如下所示:
{"code":1017,"message":"Invalid where clause. Not existing columns: "}
我遇到的问题是如何为条件语句分配变量。如果表中没有对象,并且我尝试将totalobjects\u 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
totalobjects\u start\u str=totalobjects\u search\u start.decode(encoding='utf-8')
def totalobjects_count():
尝试:
totalobjects\u start\u 1017=json.load(totalobjects\u start\u str,strict=False)['code']
除了(ValueError、KeyError、TypeError):
totalobjects\u start=int(json.load(totalobjects\u start\u str,strict=False)['totalobjects']
totalobjects_count()
如果totalobjects_start_1017==“1017”:
每(2)个工作小时
cron.write()
elif totalobjects_start<24:
通过
我对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
我对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
通常使用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
导入json
#假设以下内容来自数据库
响应='{“代码”:1017,“消息”:“where子句无效。不存在列:”}”
data=json.load(响应)
如果数据中的“代码”和数据[“代码”]==1017:
#创建cron
elif数据中的“totalObjects”和0=24时,可能有一些操作
通过
通常使用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
导入json
#假设以下内容来自数据库
响应='{“代码”:1017,“消息”:“where子句无效。不存在列:”}”
data=json.load(响应)
如果数据中的“代码”和数据[“代码”]==1017:
#创建cron
elif数据中的“totalObjects”和0=24时,可能有一些操作
通过
缩进是否正确?你能再清楚一点你想做什么吗?输入内容是什么?你希望它最终是什么?缩进是因为它看起来不正确而发布的吗?对不起,我昨天非常累,这个问题有点模棱两可。我在原来的帖子里重写了这个问题。缩进正确吗?你能再清楚一点你想做什么吗?输入内容是什么?你希望它最终是什么?缩进是因为它看起来不正确而发布的吗?对不起,我昨天非常累,这个问题有点模棱两可。我在原来的帖子里重写了这个问题。我没有试图返回code:1017
或1
。如果返回了1017
,我将尝试执行x
,如果返回了totalObjects:
,我将尝试执行y
。这是我不清楚的过错。谢谢。我在原来的帖子里重写了这个问题。我没有试图返回code:1017
或1
。如果返回了1017
,我将尝试执行x
,如果返回了totalObjects:
,我将尝试执行y
。这是我不清楚的过错。谢谢。我相信这正是我想要做的。感谢您演示如何在中使用JSON!我相信这正是我想要做的。感谢您演示如何在中使用JSON!