jq select 个项目,其中一个 属性 包含另一个 属性 的值

jq select items where a property contains the value of another property

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

data.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 中是否有一种基于动态 属性 而不是字符串文字 select 的方法?

假设您的 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