我有一个应用程序可以生成这种形式的数据:
[
{
"metadata": {
"labels": {
"team": "eng"
}
},
"spec": {
"labels": {
"instance_id": {
"result": "x387j"
}
}
}
},
{
"metadata": {
"labels": {
"team": "sre"
}
},
"spec": {
"labels": {
"instance_id": {
"result": "sd9f"
}
}
}
}
]
标签,这里是
.metadata.labels
和.spec.labels
中的按键。
我可以将标签提取为:
% jq -C ' .[] | ( .metadata.labels , .spec.labels ) | keys | .[] ' tmp/x.json | sort | uniq
"instance_id"
"team"
我想将标签和结果对提取为:
"team": "eng"
"instance_id": "x387j"
"team": "sre"
"instance_id": "sd9f"
我可以获取 .metadata.labels 中的对象,尽管形式不同:
% jq -C '.[] | (.metadata.labels) ' tmp/x.json
{
"team": "eng"
}
{
"team": "sre"
}
生成一个零件,但在这里,我无法仅删除大括号。 建议此处删除括号、引号和逗号 去掉了大括号,也去掉了键。
% jq -C '.[] | (.metadata.labels) | .[] ' tmp/x.json
"eng"
"sre"
此外,我无法弄清楚如何获取 .spec.labels 中的对象。
这会生成您预期的输出:
jq -r '.[]
| .metadata.labels
+ .spec.labels.instance_id
| to_entries[]
| map(tojson)
| join(": ")'