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