Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"
}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading