gpt4 book ai didi

python - 如果值存在,如何让 jmespath 过滤器返回 true,如果不存在,则返回 false(python)

转载 作者:行者123 更新时间:2023-12-05 05:59:24 25 4
gpt4 key购买 nike

这是对上一个未解决问题的扩展,但另一种看待问题的方式 HERE

{
"name": "Sarah",
"region": "south west",
"age": 21,
"occupation": "teacher",
"height": 145,
"education": "university",
"favouriteMovie": "matrix",
"gender": "female",
"country": "US",
"level": "medium",
"tags": [],
"data": "abc",
"moreData": "xyz",
"logging" : {
"systemLogging" : [ {
"environment" : "test",
"example" : [ "this", "is", "an", "example", "array" ]
} ]
}
}

如果我想查看 python 字典中简单键值对的值是否存在,我可以使用 jmespath 查询来实现

"occupation == `teacher`"
>> True
"occupation == `dancer`"
>> False

但是对于更复杂的数据,例如带有列表/数组的嵌套字典,我能做的最好的事情就是过滤以获得值

"logging.systemLogging[?environment == `test`] | [0].enabled"
>> test
"logging.systemLogging[?environment == `prod`] | [0].enabled"
>> None

如何让上面的示例返回 TrueFalse 而不是值(如果存在)和 None 或空数组 [] 如果没有

最佳答案

好吧,你完全可以这样做:

logging.systemLogging[?environment == `test`] | [0].enabled != null

开启

{
"name": "Sarah",
"region": "south west",
"age": 21,
"occupation": "teacher",
"height": 145,
"education": "university",
"favouriteMovie": "matrix",
"gender": "female",
"country": "US",
"level": "medium",
"tags": [],
"data": "abc",
"moreData": "xyz",
"logging": {
"systemLogging": [{
"environment": "test",
"example": ["this", "is", "an", "example", "array"]
}]
}
}

将导致

false

虽然在这个 JSON 上也是如此——添加了 logging.systemLogging[0].enabled: false:

{
"name": "Sarah",
"region": "south west",
"age": 21,
"occupation": "teacher",
"height": 145,
"education": "university",
"favouriteMovie": "matrix",
"gender": "female",
"country": "US",
"level": "medium",
"tags": [],
"data": "abc",
"moreData": "xyz",
"logging": {
"systemLogging": [{
"enabled": false,
"environment": "test",
"example": ["this", "is", "an", "example", "array"]
}]
}
}

将导致

true

关于python - 如果值存在,如何让 jmespath 过滤器返回 true,如果不存在,则返回 false(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68175161/

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