使用jq从嵌套的JSON对象中提取所选属性 [英] Extracting selected properties from a nested JSON object with jq
本文介绍了使用jq从嵌套的JSON对象中提取所选属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此给出对象的JSON数组:
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"
}
}
]
我想从嵌套的properties
中提取键/值的子集,同时保持外部对象的其他属性不变,生成类似以下内容的
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"
}
}
]
即删除除NAME
和NAME_LONG
之外的所有键.
i.e. remove all keys except NAME
and NAME_LONG
.
我确信必须有一种使用jq实现此目标的合理简便的方法.帮助表示赞赏.
I'm sure there must be a reasonably easy way of achieving this with jq. Help appreciated.
推荐答案
您可以使用以下过滤器:
You can use this filter:
map(
.properties |= with_entries(select(.key == ("NAME", "NAME_LONG")))
)
这会映射过滤出properties
对象的数组中的每个项目,使其仅包含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.
这篇关于使用jq从嵌套的JSON对象中提取所选属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文