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

How to select jq items where length of key value exceeds a number

I have this JSON input to JQjq

{
  "names": [{
    "name": "John Smith"
  },{
    "name": "Jane Doe"
  },{
    "name": "Jackson Longfellow"
  }]
}

I’d like to use jq to select all the items where the length of the name is > 10 characters. This means the output would be:

{
  "names": [{
    "name": "Jackson Longfellow"
  }]
}

The length filter only seems to count items in an array. Is there some other built-in filter to use for this?

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

>Solution :

Update |= the names array by selecting only those items that match. length applied to a string will output its length counting Unicode codepoints.

jq '.names |= map(select(.name | length > 10))'
{
  "names": [
    {
      "name": "Jackson Longfellow"
    }
  ]
}

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