gpt4 book ai didi

python - 如何正确处理 simplejson 错误?

转载 作者:行者123 更新时间:2023-11-30 23:49:05 25 4
gpt4 key购买 nike

我已将 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

这是正确的做法吗?看起来太复杂了。如果找不到值,有什么方法可以获取空值吗?

最佳答案

get() Python中有一个默认参数,如果没有找到该值,将返回默认值。

print dict.get("name", "<default name>")

关于python - 如何正确处理 simplejson 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7783876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com