使用jq在嵌套数组上删除

时间:2017-02-13 23:12:40

标签: arrays json nested jq

这是我的数据结构:

[
    {
        "name": "name1",
        "organizations": [
            {
                "name": "name2",
                "spaces": [
                    {
                        "name": "name3",
                        "otherkey":"otherval"
                    },
                    {
                        "name": "name4",
                        "otherkey":"otherval"
                    }
                ]
            }
        ]
    },
    {
        "name": "name21",
        "organizations": [
            {
                "name": "name22",
                "spaces": [
                    {
                        "name": "name23",
                        "otherkey":"otherval"
                    },
                    {
                        "name": "name24",
                        "otherkey":"otherval"
                    }
                ]
            }
        ]
    }
]

我只想保留name = name1,删除名称= name4的嵌套数组对象,并希望保持对象的其余部分不变。我尝试使用map(select),但这只会给我一个完整的对象。是否可以在特定的子阵列上使用del并保持其余的原样?

结果应如下。另外我想避免枚举所有属性以保留外部对象:

[
    {
        "name": "name1",
        "organizations": [
            {
                "name": "name2",
                "spaces": [
                    {
                        "name": "name3",
                        "otherkey":"otherval"
                    }
                ]
            }
        ]
    }
]

任何想法?谢谢!

2 个答案:

答案 0 :(得分:1)

一个非常有针对性的解决方案是:

path(.[0].organizations[0].spaces) as $target
| (getpath($target) | map(select(.name != "name4"))) as $new
| setpath($target; $new)

但是,如果允许,您可以考虑:

walk(if type == "object" and .spaces|type == "array"
     then .spaces |= map(select(.name != "name4"))
     else . end)

或:

del(.. | .spaces? // empty | .[] | select(.name == "name4") )

(如果您的jq没有walk/1,则可以通过Google搜索轻松找到其jq定义。)

答案 1 :(得分:0)

以下是使用选择减少 tostream 删除路径

的解决方案
map(  
    select(.name == "name1")
  | reduce (tostream|select(length==2)) as [$p,$v] (
      .
    ; if [$p[-1],$v] == ["name","name4"] then delpaths([$p[:-1]]) else . end
    )
)