gpt4 book ai didi

bash - jq:递归 -> 嵌套数组

转载 作者:行者123 更新时间:2023-12-04 08:10:07 26 4
gpt4 key购买 nike

如何用 jq 解析这个 json 结构?它应该递归地遍历叶子(项目和组)。
我的用例是:使用 CLI 在 VCS 中创建项目和组。组可以有多个项目,组可以为空,项目必须有预先创建的父组。
类似的比喻是:

  • 组 = 文件夹
  • 项目 = 文件
  • path = 格式的绝对路径 /root-groups/nested-groups-level-1/nested-groups-level-2/nested-groups-level-N

  • 谢谢
    {
    "structure":[
    {
    "name":"rootgroup1",
    "type":"group",
    "nested":[
    {
    "name":"nestedproject1",
    "type":"project"
    },
    {
    "name":"nestedgroup1",
    "type":"group",
    "nested":[
    {
    "name":"nestednestedproject2",
    "type":"project"
    }
    ]
    }
    ]
    },
    {
    "name":"rootproject1",
    "type":"project"
    },
    {
    "name":"rootgroup2",
    "type":"group",
    "nested": []
    }
    ]
    }
    预期输出:
    "rootgroup1","group",""
    "nestedproject1","project","rootgroup1"
    "nestedgroup1","group","rootgroup1"
    "nestednestedproject2","group","rootgroup1/nestedgroup1"
    "rootproject1","project",""
    "rootgroup2","group",""
    尝试:
    jq -r '.structure[] | .. | "\(.name?) \(.type?)"'
    仍然不确定,如何创建父路径。

    最佳答案

    以下实现了我理解的问题的解决方案:

    # $prefix is an array interpreted as the prefix
    def details($prefix):
    def out:
    select(has("name") and has("type")) | [.name, .type, "/" + ($prefix|join("/"))];

    out,
    if (.nested | (. and length>0))
    then .name as $n | .nested[] | details($prefix + [$n])
    else empty
    end;

    .structure[]
    | details([])
    | @csv
    鉴于您的样本输入,输出将是:
    "rootgroup1","group","/"
    "nestedproject1","project","/rootgroup1"
    "nestedgroup1","group","/rootgroup1"
    "nestednestedproject2","project","/rootgroup1/nestedgroup1"
    "rootproject1","project","/"
    "rootgroup2","group","/"
    这在某些方面与示例输出不同,但希望您可以从这里获取它。

    关于bash - jq:递归 -> 嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66014841/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com