【问题标题】:Unable to filter for multiple features with JMESPath无法使用 JMESPath 过滤多个功能
【发布时间】:2022-10-14 22:04:39
【问题描述】:

我的数据如下所示。为什么我能够使用包含而不是我希望过滤的单词列表来过滤一个单词? 两个查询应该产生相同的输出

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

【问题讨论】:

    标签: python jmespath


    【解决方案1】:

    函数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'}]
    

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 1970-01-01
      • 2020-06-08
      • 2023-03-24
      • 2018-12-15
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 2019-05-20
      相关资源
      最近更新 更多