对于如下所示的 Json 字段,如果 eventId 是一个连续值,我想添加消息字段的值。
但是即使eventId是连续的,如果message字段以#Time开头的话,message字段是被分割的。
这个是Json的原始字段。
{
"events": [
{
"message": "# Time: 1",
"eventId": "38636469249093328935961608873790523617989208925384015872"
},
{
"message": ", 2, 3",
"eventId": "38636469249093328935961608873790523617989208925384015873"
},
{
"message": "# Time: 11",
"eventId": "38636469249093328935961608873790523617989208925384015875"
},
{
"message": "# Time: 12",
"eventId": "38636469249093328935961608873790523617989208925384015876"
},
{
"message": "# Time: A",
"eventId": "1"
},
{
"message": ", B, C",
"eventId": "2"
},
{
"message": "# Time: C",
"eventId": "3"
},
{
"message": "# Time: D",
"eventId": "5"
}
]
}
我想要的效果如下:
[
{
"message": "# Time: 1, 2, 3"
},
{
"message": "# Time: 11"
},
{
"message": "# Time: 12"
},
{
"message": "# Time: A , B, C"
},
{
"message": "# Time: C"
},
{
"message": "# Time: D"
}
]
我之前问过这个问题,得到了一个好人的回答。(谢谢 pmf。)
之后,我尽力对其进行了进一步的改进,但没有成功,所以我又问了一次。
首先,当我第一次运行这个 JQ 时,我得到了以下结果。
jq -r '.events
| reduce .[1:][] as $i (.[:1];
if ((.[-1].eventId | tonumber + 1 | tostring) != $i.eventId) or ($i.message | startswith("# Time:")) then
. += [$i]
else
.[-1].message += " " + $i.message
end
)
| del(.[].eventId)
'
[
{
"message": "# Time: 1"
},
{
"message": ", 2, 3"
},
{
"message": "# Time: 11"
},
{
"message": "# Time: 12"
},
{
"message": "# Time: A , B, C"
},
{
"message": "# Time: C"
},
{
"message": "# Time: D"
}
]
我将其视为浮点问题,并想将这个数字与字符串本身进行比较,因此我创建了一个如下函数,但它不起作用。
jq '
# Function to add one to a large number represented as a string
def add_one(num):
(num | split("") | reverse | map(tonumber)) as $digits
| reduce range(0; length) as $i ([];
. + if $i == 0 or .[-1] == 10 then
[($digits[$i] + 1) % 10]
else
[$digits[$i]]
end
)
| reverse | map(tostring) | join("");
# Process events and check continuity
.events
| map(.eventId |= tostring) # Ensure all eventIds are strings
| reduce .[1:][] as $i (.[:1];
if (add_one(.[-1].eventId) != $i.eventId) or ($i.message | startswith("# Time:")) then
. += [$i]
else
.[-1].message += " " + $i.message
end
)
| del(.[].eventId)
'
[
{
"message": "# Time: 1"
},
{
"message": ", 2, 3"
},
{
"message": "# Time: 11"
},
{
"message": "# Time: 12"
},
{
"message": "# Time: A"
},
{
"message": ", B, C"
},
{
"message": "# Time: C"
},
{
"message": "# Time: D"
}
]
当我进一步搜索时,我发现了一个名为 gojq 的命令,但我想先测试一下它,看看是否可以用 jq 来实现。
我正在使用 jq 版本 1.7.1。