JQ~折叠特定的单对象数组? [英] jq ~ collapse specific single object arrays?
本文介绍了JQ~折叠特定的单对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对应于jq ~ is there a better way to collapse single object arrays?和R: Nested data.table to JSON 如何仅折叠特定元素?
我想删除
中的";group";数组[
{
"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)'
行另外从单个";data";对象中删除数组。
不幸的是,我们不能在我们的RStudio服务器上安装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~折叠特定的单对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文