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 only scalars in objects in JSON array?

I have the following JSON data structure I’d like to filter using jq:

{
 "data": [
  {
   "id": "blah",
   "foo": "bar",
   "array": [ ... ]
  },
  {
   "id": "blah",
   "foo": "bar"
   "array": [ ... ]
  }
 ]
}

I want to map this to an array of objects with only the top-level scalar values present in each modified object (i.e. keys containing values like arrays and objects should disappear—I’m not interested in the contents of anything nested here):

[
  {
   "id": "blah",
   "foo": "bar"
  },
  {
   "id": "blah",
   "foo": "bar"
  }
]

This should be possible using some combination of jq‘s map and select operators in tandem with scalars, but I am unable to figure out an exact solution. I expect the answer to be embarrassingly simple. For example, I have tried .data[] | map(select(scalars)), etc.

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

I am using the latest version of jq.

>Solution :

The with_entries builtin lets you select upon the value while retaining the object-field structure.

jq '.data | map(with_entries(select(.value | scalars)))'
[
  {
    "id": "blah",
    "foo": "bar"
  },
  {
    "id": "blah",
    "foo": "bar"
  }
]

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