jq ~ 折叠特定的单个对象数组?
jq ~ collapse specific single object arrays?
对应jq ~ is there a better way to collapse single object arrays? and
如何仅折叠特定元素?
我想摆脱
中的“组”数组
[
{
"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 Server 上安装 jq 1.6 版本,因此我无法使用 walk 功能。 (尽管在我的本地系统上运行良好)
任何人都可以帮我找到一个无需步行的替代解决方案吗?将不胜感激。
编辑
好,我知道了。我可以手动添加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)'
我们可以在嵌套层次结构中操作更高一层,并测试 "group"
是否为键,然后相应地更新 .group = .group[0]
而不是 . = .[0]
jq 'walk(if type=="object"
and has("group")
and (.group | type)=="array"
and (.group | length)==1
then .group = .group[0]
else . end)'
对应jq ~ is there a better way to collapse single object arrays? and
我想摆脱
中的“组”数组[
{
"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 Server 上安装 jq 1.6 版本,因此我无法使用 walk 功能。 (尽管在我的本地系统上运行良好)
任何人都可以帮我找到一个无需步行的替代解决方案吗?将不胜感激。
编辑 好,我知道了。我可以手动添加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)'
我们可以在嵌套层次结构中操作更高一层,并测试 "group"
是否为键,然后相应地更新 .group = .group[0]
而不是 . = .[0]
jq 'walk(if type=="object"
and has("group")
and (.group | type)=="array"
and (.group | length)==1
then .group = .group[0]
else . end)'