I'm trying to filter for items from a list that contain the values of other properties in the same object.
Example of the data.json:
{ result:
[
{ name: 'foo', text: 'my name is foo' },
{ name: 'bar', text: 'my name is baz' },
]
}
What I've tried:
cat data.json | jq '.result[] | select(.text | ascii_downcase | contains(.name))'
However it throws the following error:
Cannot index string with string
Is there a way in jq to select based on a dynamic property rather than a string literal?
CodePudding user response:
Assuming your JSON looks more like this (strings in double quotes, no comma after the last array item):
{ "result":
[
{ "name": "foo", "text": "my name is foo" },
{ "name": "bar", "text": "my name is baz" }
]
}
When going into .text
, you have lost the context from which you can access .name
. You could save it (or directly the desired value) in a variable and reference it when needed:
jq '.result[] | select(.name as $name | .text | ascii_downcase | contains($name))'
{
"name": "foo",
"text": "my name is foo"
}