9

Given a JSON array of objects thus:

[
  {
    "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": "U.K.",
      "BRK_A3": "AIA",
      "TYPE": "Dependency",
      "NAME_LONG": "Anguilla"
    }
  }
]

I'd like to extract a subset of the key/values from the nested properties, whilst keeping other properties from the outer object intact, producing 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. remove all keys except NAME and NAME_LONG.

I'm sure there must be a reasonably easy way of achieving this with jq. Help appreciated.

Rob Cowie
  • 22,259
  • 6
  • 62
  • 56

2 Answers2

9

You can use this filter:

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

This maps each item in the array where the properties object is filtered to only include the NAME and NAME_LONG properties.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • Is there a way to pass in the names of the keys as a variable to jq? or does constructing the right hand side of `==` need to be done by interpolation? – GcL Feb 06 '20 at 16:07
8

map(.properties |= {NAME, NAME_LONG}) is more straight-forward and understandable.

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

user4011114
  • 109
  • 1
  • 2