【问题标题】:Handle a KeyError while parsing JSON解析 JSON 时处理 KeyError
【发布时间】:2015-08-12 01:15:05
【问题描述】:

初学者问题。

我正在卷曲我的数据库以查看某个对象是否存在于某个 requestId 中。

理想情况下,我的代码应该是这样的:

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

当具有该 requestId 的表中存在 1+ 个对象时,这很好。注意属性totalObjects1

{"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

【问题讨论】:

  • 缩进是否正确?你能更清楚地知道你想做什么吗?输入是什么,你希望它最终是什么?
  • 缩进是否因为看起来不正确而发布?
  • 对不起,昨天太累了,问题有点含糊。我在原始帖子中重写了问题。

标签: python json python-3.x


【解决方案1】:

通常使用 in 关键字来检查字典中是否存在键。如果您还不知道这一点 - 当您在 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

【讨论】:

  • 我相信这正是我想要做的。感谢您演示如何将 in 与 JSON 一起使用!
【解决方案2】:

我对 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

【讨论】:

  • 我在原来的帖子中重写了这个问题。我不想返回code: 10171。如果返回1017,我正在尝试执行x,如果返回totalObjects: _,我正在尝试执行y。那是我不清楚的错。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
相关资源
最近更新 更多