我有很多JSON对象,看起来如下所示,我想做的是转换每个对象,除了小的调整,名为last的节点,添加长度节点,所以最后,我们有每个部分的长度总和:
输入示例JSON对象
{
"serialnumber": "5690",
"duplicate": true,
"parts": [
{
"serialnumber": "43",
"position_in": true,
"duplicate": true,
"positions": [
{
"self": 0,
"length": 3
},
{
"self": 4,
"length": 1
},
{
"self": 5,
"length": 2
}
]
},
{
"serialnumber": "745",
"position_in": true,
"duplicate": false,
"positions": [
{
"self": 0,
"length": 8
},
{
"self": 8,
"length": 1
},
{
"self": 9,
"length": 1
}
]
}
]
}
所需的JSON输出:
{
"5690": {
"duplicate": true,
"parts": {
"43": {
"position_in": true,
"duplicate": true,
"last": "7"
},
"745": {
"position_in": true,
"duplicate": false,
"last": "10"
}
}
}
}
如何使用jq和+运算符实现所需的结果?
答案 0 :(得分:1)
这里的技巧是定义辅助函数:
# Given a part, extract the desired bits and the sum of the lengths:
def part:
{ (.serialnumber):
{position_in,
duplicate,
last: (.positions | map(.length) | add) }};
现在我们可以基本上写下我们想要的声明:
{ (.serialnumber): { duplicate, "parts": (.parts | map(part) ) } }
使用sample.json中的数据,以及名为program.jq的文件中的上述内容,调用:
jq -f program.jq sample.json
产生
{
"5690": {
"duplicate": true,
"parts": [
{
"43": {
"position_in": true,
"duplicate": true,
"last": 6
}
},
{
"745": {
"position_in": true,
"duplicate": false,
"last": 10
}
}
]
}
}