在处理嵌套的JSON对象时,可以使用安全的方式来获取值,以避免抛出异常。以下是一些解决方法的示例代码。
import json
data = '{"key1": {"key2": {"key3": "value"}}}'
try:
json_data = json.loads(data)
value = json_data.get('key1', {}).get('key2', {}).get('key3')
print(value)
except (ValueError, AttributeError, TypeError, KeyError):
print("Error: Unable to get the value from JSON")
import json
data = '{"key1": {"key2": {"key3": "value"}}}'
def get_nested_value(json_data, keys):
try:
if len(keys) == 1:
return json_data.get(keys[0])
else:
return get_nested_value(json_data.get(keys[0], {}), keys[1:])
except (AttributeError, TypeError, KeyError):
return None
json_data = json.loads(data)
keys = ['key1', 'key2', 'key3']
value = get_nested_value(json_data, keys)
print(value)
这两种方法都可以安全地获取嵌套的JSON对象值,即使某个键不存在或者数据类型不匹配也不会引发异常。