Python检查json数组中是否存在值
我有以下python脚本Python检查json数组中是否存在值,python,json,Python,Json,我有以下python脚本 def main(): json_obj = { "attributes": [ { "key": "some key", "value": "hello" } ] } needle = "he
def main():
json_obj = {
"attributes": [
{
"key": "some key",
"value": "hello"
}
]
}
needle = "hello"
if needle in json_obj["attributes"]:
print("yay")
if __name__ == "__main__":
main()
现在我不明白为什么print语句返回false。针肯定在列表中。这可能是重复的,但您正在字典中进行签入检查,默认情况下只检查键:
"key" in {"key": "some key", "value": "hello"}
将产生false,因为它类似于:
"key" in {"key": "some key", "value": "hello"}.keys()
鉴于
"hello" in {"key": "some key", "value": "hello"}.values()
将产生True
json_obj[“属性”]
是一个dict。。。。因此有两个错误,您需要进行额外的检查,正如@ekhumoro所说的-正确的检查是如果针在json_obj[“attributes”][0]。values()
@Crunchie问题定义不清。搜索是否真的要搜索任何等于指针的值?OP似乎更希望找到“value”等于指针的元素。