我有来自 Junos REST API 的以下 JSON 文档。我正在尝试将文档简化为仅选定的几个项目。我将如何实现这个目标?
预期的 JSON:
[
{ "status": .member-status[0].data,
"serial": .member-serial-number[0].data,
"slot": .fpc-slot[0].data
},
...
]
原始 JSON:
{
"member-status": [
{
"data": "Prsnt"
}
],
"member-id": [
{
"data": "0"
}
],
"fpc-slot": [
{
"data": "(FPC 0)"
}
],
"member-serial-number": [
{
"data": "serNo1"
}
],
"member-model": [
{
"data": "ex4400-24t"
}
],
"member-priority": [
{
"data": "255"
}
],
"member-mixed-mode": [
{
"data": "N"
}
],
"member-route-mode": [
{
"data": "VC"
}
],
"member-role": [
{
"data": "Master*"
}
],
"neighbor-list": [
{}
]
}
{
"member-status": [
{
"data": "NotPrsnt"
}
],
"member-id": [
{
"data": "1"
}
],
"fpc-slot": [
{
"data": "(FPC 1)"
}
],
"member-serial-number": [
{
"data": "serNo2"
}
],
"member-model": [
{}
]
}
答案1
应该是这样的:
jq -s '
map(
{
"status": ."member-status"[0].data,
"serial": ."member-serial-number"[0].data,
"slot" : ."fpc-slot"[0].data
}
)' your-file.json
或者稍微分解一下代码:
jq -s '
map({
"status": ."member-status",
"serial": ."member-serial-number",
"slot" : ."fpc-slot"
} | with_entries(.value |= .[0].data))' your-file.json
或者,因为所有三个的简化键恰好是第二个-
分隔的单词:
jq -s '
map({"member-status", "member-serial-number", "fpc-slot"} |
with_entries(.value |= .[0].data | .key |= split("-")[1]))' your-file.json
您的样本给出了:
[
{
"status": "Prsnt",
"serial": "serNo1",
"slot": "(FPC 0)"
},
{
"status": "NotPrsnt",
"serial": "serNo2",
"slot": "(FPC 1)"
}
]
-s
将输入中的多个串联 JSON 合并到一个 JSON 数组中,并将map()
指定的对象映射到每个成员。作为 的替代方案map({...})
,您还可以[ .[] | {...} ]
对数组成员进行迭代并根据结果构建一个新数组。