Extract selected properties from nested JSON object using jq

Given an array of JSON objects this way:

[ { "geometry": { "type": "Polygon", "coordinates": [[[-69.9969376289999, 12.577582098000036]]] }, "type": "Feature", "properties": { "NAME": "Aruba", "WB_A2": "AW", "INCOME_GRP": "2. High income: nonOECD", "SOV_A3": "NL1", "CONTINENT": "North America", "NOTE_ADM0": "Neth.", "BRK_A3": "ABW", "TYPE": "Country", "NAME_LONG": "Aruba" } }, { "geometry": { "type": "MultiPolygon", "coordinates": [[[-63.037668423999946, 18.212958075000028]]] }, "type": "Feature", "properties": { "NAME": "Anguilla", "WB_A2": "-99", "INCOME_GRP": "3. Upper middle income", "SOV_A3": "GB1", "NOTE_ADM0": "UK", "BRK_A3": "AIA", "TYPE": "Dependency", "NAME_LONG": "Anguilla" } } ] 

I would like to extract a subset of the key / values ​​from the nested properties , while keeping the other properties from the external object intact, creating something like:

 [ { "geometry": { "type": "Polygon", "coordinates": [[[-69.9969376289999, 12.577582098000036]]] }, "type": "Feature", "properties": { "NAME": "Aruba", "NAME_LONG": "Aruba" } }, { "geometry": { "type": "MultiPolygon", "coordinates": [[[-63.037668423999946, 18.212958075000028]]] }, "type": "Feature", "properties": { "NAME": "Anguilla", "NAME_LONG": "Anguilla" } } ] 

i.e. delete all keys except NAME and NAME_LONG .

I am sure there should be a fairly simple way to achieve this with jq. Help evaluate.

+4
source share
2 answers

You can use this filter:

 map( .properties |= with_entries(select(.key == ("NAME", "NAME_LONG"))) ) 

This displays each element in the array, where the properties object is filtered only to include the NAME and NAME_LONG .

+5
source

map(.properties |= {NAME, NAME_LONG}) more straightforward and straightforward.

I would add this as a comment to Jeff's answer, but the SO rules on comments are stupid, so instead it goes as an answer.

+3
source

All Articles