代码之家  ›  专栏  ›  技术社区  ›  Danny Delott

jq选择一个属性包含另一个属性值的项

  •  0
  • Danny Delott  · 技术社区  · 4 年前

    我试图从包含同一对象中其他属性值的列表中筛选项目。

    数据示例。json:

    { result: 
      [
        { name: 'foo', text: 'my name is foo' },
        { name: 'bar', text: 'my name is baz' },
      ]
    }
    

    我试过的:

    cat data.json | jq '.result[] | select(.text | ascii_downcase | contains(.name))'
    

    但是,它会抛出以下错误: Cannot index string with string

    在jq中,有没有一种基于动态属性而不是字符串文本进行选择的方法?

    1 回复  |  直到 4 年前
        1
  •  1
  •   pmf    4 年前

    假设JSON看起来更像这样(字符串用双引号括起来,最后一个数组项后面没有逗号):

    { "result": 
      [
        { "name": "foo", "text": "my name is foo" },
        { "name": "bar", "text": "my name is baz" }
      ]
    }
    

    当进入 .text ,您失去了可以访问的上下文 .name 。您可以将其(或直接将所需值)保存在变量中,并在需要时引用它:

    jq '.result[] | select(.name as $name | .text | ascii_downcase | contains($name))'
    
    {
      "name": "foo",
      "text": "my name is foo"
    }
    

    Demo