为了账号安全,请及时绑定邮箱和手机立即绑定

Python 检查 json 以确保字段不存在

Python 检查 json 以确保字段不存在

慕姐4208626 2023-09-12 19:54:55
我有一个 python 函数,我想检查传递的 json 中是否存在某个字段。本质上,如果该字段存在,我想抛出一个错误。我有一些有用的东西,但看起来不太好,所以我认为有一个更好的解决方案:def check_groups(names):    json_names = json.loads(names)    for i in json_names:        try:            #check to make sure no groups have been passed through            if(i['groups']):                print('in if')                raise Exception()        except TypeError:            #this means there is no groups in the json so all is ok            print('ok')        except Exception:            raise Exception('Do not pass through groups')正如你所看到的,这在逻辑上并不是很好,而且我显然必须在 TypeError 之外添加一行代码(在这种情况下,print('ok')我真的不想/不需要这样做。本质上,如果 json 有一个名为 的字段groups,我想抛出一个错误。如果没有,请继续。json 很简单,下面是提供了不需要的字段后的示例:[{"field_1": ["$.id"], "groups": "ABC"}]
查看完整描述

1 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

尝试类似的东西


def check_groups(names):

    json_names = json.loads(names)

    for i in json_names:

        if 'groups' in i:

            raise AttributeError('Do not pass through groups')

        else:

            print('ok')

您可以使用关键字轻松测试键是否在字典中in。


查看完整回答
反对 回复 2023-09-12
  • 1 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信