Skip to main content
 首页 » 编程设计

Python:如果 abc 在 j ['category' ]

2025年05月04日15insus

给定一个如下所示的 JSON 文件:

"foobar": [ 
    { 
        "a": "true", 
        "b": 1, 
        "c": 1234, 
        "d": 9, 
        "e": "red" 
    }, 
    { 
        "a": "false", 
        "b": 2, 
        "c": 2345, 
        "d": 7, 
        "e": "green" 
    }, 
    { 
        "a": "whocares", 
        "b": 3, 
        "c": 3456, 
        "d": 5, 
        "e": "blue" 
    } 
] 

是否可以在没有循环的情况下检查“蓝色”是否出现在任何中?

import simplejson 
j = json.loads(superfile().text) 
if "blue" in j['foobar'][ANYONE]['e'] 

请您参考如下方法:

作为@jonrsharpe提到,你最好的选择可能是使用 any , 例如

if any('blue' in i['e'] for i in j['foobar']) 

或者

if any('blue' == i['e'] for i in j['foobar'])