【问题标题】:Find if the key and value pair exist in a json查找 json 中是否存在键值对
【发布时间】:2018-10-29 03:40:06
【问题描述】:

我正在尝试查看 python 中的 JSON 中是否存在键值对。

这是我所拥有的:

{
    "cars": [
        {
            "model": "test"
        },
        {
            "model": "test2"
        }
    ]
}

我试过这个:

jsondata = open("test.json",'r').read() 
fileData = json.loads(jsondata)

if "test" in [cars.model for cars in fileData]:
    print('test')

任何帮助将不胜感激。

【问题讨论】:

    标签: python arrays python-3.x python-2.7


    【解决方案1】:

    我建议的最好方法是使用 dict 和异常处理。每当找不到特定键时,就会引发“KeyError”异常,如果该键不存在,这将允许您执行必要的操作。

    在你的情况下:

    jsondata = open("test.json",'r').read() 
    fileData = json.loads(jsondata)
    
    try:
      cars = fileData['cars']
    except KeyError:
      print("Missing cars key")
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      试试这个:

      if "test" in [cars['model'] for cars in fileData['cars']]:
          print('test')
      

      更新:

      print([cars for cars in fileData['cars'] if cars['model']=='test'])
      

      只需要做一个列表理解

      【讨论】:

      • 我如何打印匹配的模型?...它进入 if 但现在我想打印那个精确的模型,因为我动态地做它
      • @HeelMega Now??
      猜你喜欢
      • 2022-07-12
      • 1970-01-01
      • 2014-01-15
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2021-06-27
      相关资源
      最近更新 更多