【问题标题】:parsing the Json for the Optional fields解析可选字段的 Json
【发布时间】:2015-12-04 01:01:00
【问题描述】:

我有以下格式的 JSON:

{  
    "type":"MetaModel",
    "attributes":[  
        {  
            "name":"Code",
            "regexp":"^[A-Z]{3}$"
        },
        {
            "name":"DefaultDescription",
        },
   ]
}

attributes["regexp"] 是可选的。当我尝试访问像 attribute["regexp"] 这样的字段时,我收到的错误是

KeyError: 'regexp'

假设是,如果该字段不存在,那么它将被视为 NULL。

如何访问可选字段?

【问题讨论】:

  • attributes[0]["regexp"]
  • 您可以使用 attributes.get('regexp') 来完成。如果未找到密钥,则返回 None。

标签: python json regex


【解决方案1】:

使用get,一种字典方法,如果键不存在,将返回None:

foo = json.loads(the_json_string)
value = foo.get('regexp')
if value:
   # do something with the regular expression

你也可以只捕获异常:

value = None
try:
    value = foo['regexp']
except KeyError:
    # do something, as the value is missing
    pass
if value:
    # do something with the regular expression

【讨论】:

    【解决方案2】:

    您可以使用attributes[0]['regexp'],因为正则表达式在属性列表中

    【讨论】:

      【解决方案3】:
          >>>data = {  
      "type":"MetaModel",
      "attributes":[  
          {  
              "name":"Code",
              "regexp":"^[A-Z]{3}$"
          },
          {
              "name":"DefaultDescription",
          },
      ]
      }
          >>>>c = data['attributes'][0].get('regexp')
          >>>>print c # >>> '^[A-Z]{3}$'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 2012-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多