如何正确处理simplejson错误?

时间:2011-10-16 11:08:37

标签: python simplejson

我已将json数据加载到api_result变量。现在我需要提取特定字段(namesurnamecity等。我该如何验证他们是否在那里?

api_result = json.loads(some_json_data)
if api_result.get('name'):
    # do something with name
if api_result.get('surname'):
    # do something with surname
if api_result.get('city'):
    # do something with city

这是正确的做法吗?看起来太复杂了。如果找不到值,有没有办法获得空值?

1 个答案:

答案 0 :(得分:3)

Python中的

get()有一个默认参数,如果找不到该值,则会重新调整默认值。

print dict.get("name", "<default name>")
相关问题