【问题标题】:Python: How to check if JSON item exists?Python:如何检查 JSON 项目是否存在?
【发布时间】:2026-02-07 02:20:03
【问题描述】:
{
  "data": [
    {
      "name": "john",
      "information": {
        "age": "20",
        "height": "6'0",
        "fav_quote": "age is just a number",
        "sports": [
          "soccer",
          "basketball",
          "baseball",
          "football",
          "hockey"
        ], 

        ...

      }
    }
  ]
}

如果我通过info = json.loads(myjsonthatsabove) 获得此信息,我该如何检查“年龄”是否存在,因为 json 中的信息可能不同且并非总是如此。如何检查sports[3](足球)是否存在,或找出运动数组中有多少项?

if 'age' in info['data'][0]['information']:
    //code

检查年龄是否存在,但这是检查所有['信息'],例如,如果['fav_quote']中有'年龄',它会起作用吗?如何查看这些信息?

【问题讨论】:

  • 就像任何其他包含列表的字典一样

标签: python json


【解决方案1】:

如何检查运动[3](足球)是否存在 或者找出运动数组中有多少项?

使用len(object),您阅读文档了吗?

for item in info['data']:
    print '%s is practicing %d sport(s)' % (
        item['name'],
        len(item['information']['sports']),
    )

【讨论】: