给定这个 json 字符串,如果 code 等于 4003,我如何提取 id 的值?
error_json = '''{
'error': {
'meta': {
'code': 4003,
'message': 'Tracking already exists.',
'type': 'BadRequest'
},
'data': {
'tracking': {
'slug': 'fedex',
'tracking_number': '442783308929',
'id': '5b59ea69a9335baf0b5befcf',
'created_at': '2018-07-26T15:36:09+00:00'
}
}
}
}'''
我不能假设除了 error 元素之外的任何东西都存在于开头,所以 meta 和 code 元素可能或可能不在那里。 data、tracking 和 id 可能存在也可能不存在。
问题是如果元素都在,如何提取id的值。如果缺少任何元素,则 id 的值应为 None
请您参考如下方法:
Python 字典有一个 get(key, default) 方法,它支持在找不到键时返回默认值。您可以链接空字典以访问嵌套元素。
# use get method to access keys without raising exceptions
# see https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html
code = error_json.get('error', {}).get('meta', {}).get('code', None)
if code == 4003:
# change id with _id to avoid overriding builtin methods
# see https://docs.quantifiedcode.com/python-anti-patterns/correctness/assigning_to_builtin.html
_id = error_json.get('error', {}).get('data', {}).get('tracking', {}).get('id', None)
现在,给定一个看起来像 JSON 的字符串,您可以使用 json.loads() 将其解析为字典,如 Parse JSON in Python 所示。
