给出以下结构:
[
{
"authorizedKey": "0",
"description": "This key is for system testing.",
"keyExpiration": "2035-02-02T18:28:59Z",
"keyId": "aaa12345-1234-1234-1234-1234567890ab"
},
{
"authorizedKey": "1",
"description": "This key is for system testing.",
"keyExpiration": "2035-02-02T18:28:59Z",
"keyId": "bbb12345-1234-1234-1234-1234567890ab"
},
{
"authorizedKey": "1",
"description": "This key is for system testing.",
"keyExpiration": "2035-02-02T18:28:59Z",
"keyId": "ccc12345-1234-1234-1234-1234567890ab"
}
]
仅使用jq
,有没有办法将其转换为以下结构?
还是需要将其包装在某种外部逻辑中?
[
{
"authorizedKey": "zero",
"description": "This key is for system testing.",
"keyExpiration": "2035-02-02T18:28:59Z",
"keyId": "aaa12345-1234-1234-1234-1234567890ab"
},
{
"authorizedKey": "one",
"description": "This key is for system testing.",
"keyExpiration": "2035-02-02T18:28:59Z",
"keyId": "bbb12345-1234-1234-1234-1234567890ab"
},
{
"authorizedKey": "one",
"description": "This key is for system testing.",
"keyExpiration": "2035-02-02T18:28:59Z",
"keyId": "ccc12345-1234-1234-1234-1234567890ab"
}
]
答案 0 :(得分:1)
这有效:
map(. + {authorizedKey: {"0": "zero", "1": "one"}[.authorizedKey]})
如果除了0和1之外还有其他值,可以将它们添加到地图中。如果您还有很多想要提高可读性,可以这样做:
{"0": "zero", "1": "one"} as $mapping |
map(. + {authorizedKey: $mapping[.authorizedKey]})
避免在代码中间编写值映射。
之所以可行,是因为+
运算符是在jq中的对象上定义的,并且如果LHS中已经存在RHS中的键,则其值将被RHS中的相应值替换。