jq 1.5当父级未知时,通过正则表达式查找嵌套元素

问题描述 投票:0回答:1

鉴于下面的JSON结构,我想找到第一次出现的对象ccc,所以我可以向孩子ddd添加一个新对象。但是,我不知道父母的关键名称或者可能有多少级别。

找到

"children": {
    "ccc": [{
        "id": "ddd",
        "des": "object d",
        "parent": "ccc"
    }]
}

存储在$ myJson中的完整JSON

{
"zzz": [{
    "id": "aaa",
    "des": "object A",
    "parent": "zzz",
    "children": {
        "aaa": [{
            "id": "bbb",
            "des": "object B",
            "parent": "aaa",
            "children": {
                "bbb": [{
                    "id": "ccc",
                    "des": "object C",
                    "parent": "bbb",
                    "children": {
                        "ccc": [{
                            "id": "ddd",
                            "des": "object d",
                            "parent": "ccc"
                        }]
                    }
                }, {
                    "id": "eee",
                    "des": "object e",
                    "parent": "bbb"
                }]
            }
        },{
            "id": "fff",
            "des": "object f",
            "parent": "aaa"
        }]
    }
}]} 

按照其他一些答案,我尝试过组合

output=($(jq -r '.. | with_entries(select(.key|match("ccc";"i")))' <<< ${myjson}))

要么

output=($(jq -r '.. | to_entries | map(select(.key | match("ccc";"i"))) | map(.value)' <<< ${myjson}))

都给出了类似性质的错误jq: error (at <stdin>:1): number (0) cannot be matched, as it is not a string

regex bash jq
1个回答
0
投票

在下面,我假设您要在与给定正则表达式匹配的每个键(此处为“ccc”)处向数组添加“ADDITIONAL”:

walk(if type == "object"
     then with_entries(if (.key|test("ccc"))
                       then .value += ["ADDITIONAL"] else . end)
     else . end)

如果你的jq没有walk/1,那么你可以简单地从jq FAQbuiltin.jq复制并粘贴它的def

Alternative formulation

如果您有以下通用辅助函数(例如在您的〜/ .jq中):

def when(filter; action): if (filter?) // null then action else . end;

然后上面的解决方案缩小到:

walk(when(type == "object";
     with_entries(when(.key|test("ccc"); .value += ["ADDITIONAL"]))))
© www.soinside.com 2019 - 2024. All rights reserved.