【发布时间】:2021-12-31 22:31:09
【问题描述】:
对应jq ~ is there a better way to collapse single object arrays?和R: Nested data.table to JSON 如何仅折叠特定元素?
我想摆脱
中的“组”数组[
{
"id2": "A",
"group": [
{
"data": [
{
"id1": 1,
"group": [
{
"data": [
{
"a": 1,
"b": 1
},
{
"a": 2,
"b": 2
}
],
"type": "test"
}
],
"type": "B"
}
],
"type": "C"
}
]
},
{
"id2": "C",
"group": [
{
"data": [
{
"id1": 3,
"group": [
{
"data": [
{
"a": 1,
"b": 1
}
],
"type": "test"
}
],
"type": "B"
}
],
"type": "C"
}
]
}
]
想要的输出
[{
"id2": "A",
"group": {
"data": [{
"id1": 1,
"group": {
"data": [{
"a": 1,
"b": 1
},
{
"a": 2,
"b": 2
}
],
"type": "test"
},
"type": "B"
}],
"type": "C"
}
},
{
"id2": "C",
"group": {
"data": [{
"id1": 3,
"group": {
"data": [{
"a": 1,
"b": 1
}],
"type": "test"
},
"type": "B"
}],
"type": "C"
}
}
]
'walk(if type=="array" and length==1 then .[0] else . end)' 行还从单个“数据”对象中删除了数组。
不幸的是,我们无法在我们的 RStudio 服务器上安装 jq 1.6 版本,因此我无法使用 walk 功能。 (虽然在我的本地系统上工作得很好)
任何人都可以帮助我提供无需步行的替代解决方案吗?将不胜感激。
编辑 好,我知道了。我可以手动添加步行功能,例如:
'def walk(f):
. as $in
| if type == "object" then
reduce keys_unsorted[] as $key
( {}; . + { ($key): ($in[$key] | walk(f)) } ) | f
elif type == "array" then map( walk(f) ) | f
else f
end; walk(if type=="object"
and has("group")
and (.group | type)=="array"
and (.group | length)==1
then .group = .group[0]
else . end)'
【问题讨论】: