我的数据如下所示。为什么我可以使用包含而不是我想要筛选的单词列表来筛选一个单词?两个查询都应该产生相同的输出
import jmespath
data = {'collection': {'items': {'word': 'ice-cube'}}}
jmespath.search(
'values(collection)[?word!=null && contains([`cube`,`-`],word)]',
data
) # returns []
jmespath.search(
'values(collection)[?word!=null && contains(word,`cube`)]',
data
) # works
函数contains
的签名是
boolean contains(array|string $subject, any $search)
所以,当你进行时
contains([`cube`, `-`], word)
您实际上是在数组[`cube`, `-`]
中查找属性word
的值,而不是像在中那样反过来查找
contains(word, `cube`)
您确实在属性word
的值中搜索cube
。
此外:
如果
$subject
是一个数组,则如果数组中的一个元素等于提供的$search
值,则此函数将返回true。
来源:https://jmespath.org/specification.html#contains
这意味着你必须与你在主题中搜索的内容完全匹配,而这不是你在这里想要做的。
根据您的需求,您将不得不构建具有多个包含项的查询:
collection.* | [?word && contains(word, `-`) && contains(word, `cube`)]
这很容易做到,因为您使用Python库进行查询。
例如:
import jmespath
data = {'collection': {'items': {'word': 'ice-cube'}}}
terms = {'cube', '-'}
contains = [f'contains(word, `{term}`)' for term in terms]
print(
jmespath.search(
f'collection.* | [?word && {" && ".join(contains)}]',
data
)
)
收益率:
[{'word': 'ice-cube'}]