使用jq从嵌套的JSON对象中提取选定的属性

时间:2015-03-25 15:01:11

标签: json jq

给定一个JSON对象数组:

[
  {
    "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"
    }
  }
]

我想从嵌套的properties中提取键/值的子集,同时保持外部对象的其他属性不变,产生如下内容:

[
  {
    "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"
    }
  }
]

即。删除除NAMENAME_LONG以外的所有密钥。

我确信必须有一个相当简单的方法来实现这个jq。帮助赞赏。

2 个答案:

答案 0 :(得分:6)

您可以使用此过滤器:

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

这会将数组中过滤了properties对象的每个项目映射为仅包含NAMENAME_LONG属性。

答案 1 :(得分:4)

map(.properties |= {NAME, NAME_LONG})更直接,更容易理解。

我将此添加为对Jeff的答案的评论,但关于评论的SO规则是愚蠢的,所以它作为答案而已。