8

因此,给定一个 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"
    }
  }
]

即删除除NAMEand之外的所有键NAME_LONG

我确信一定有一种相当简单的方法可以用 jq 实现这一点。帮助表示赞赏。

4

2 回答 2

8

您可以使用此过滤器:

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

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

于 2015-03-25T15:10:50.673 回答
6

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

我会将此作为评论添加到 Jeff 的答案中,但是关于评论的 SO 规则很愚蠢,所以它作为答案来代替。

于 2016-04-01T09:14:35.180 回答