如何使用`jq`通过组合一些值来转换json?

时间:2015-06-19 07:54:00

标签: json jq

说我有一个JSON:

{
    "name":"my-project",
    "projects" : [
    {
        "project": "core",
        "configurations": [
        {
            "configuration": "compile",
            "dependencies" : [
                {
                    "organization": "a11",
                    "name" : "b11",
                    "version" : "1.1"
                },
                {
                    "organization": "a22",
                    "name" : "b22",
                    "version" : "2.2",
                    "dependencies" : [
                         {
                            "organization": "a33",
                            "name" : "b33",
                            "version" : "3.3"
                        }
                    ]
                }
            ]
        }
        ]
    }
    ]
}

如何使用jq将JSON转换为:

{
    "name":"my-project",
    "projects" : [
    {
        "project": "core",
        "configurations": [
        {
            "configuration": "compile",
            "dependencies" : [
                {
                    "dep" : "a11:b11:1.1"
                },
                {
                    "dep": "a22:b22:2.2",
                    "dependencies" : [
                         {
                            "dep": "a33:b33:3.3"
                        }
                    ]
                }
            ]
        }
        ]
    }
    ]
}

1 个答案:

答案 0 :(得分:2)

在函数的帮助下,您可以递归执行此操作。

def update_dependencies:
    { dep: "\(.organization):\(.name):\(.version)" }
    +
    with_entries(select(.key == "dependencies") | .value |= map(update_dependencies))
    ;
.projects |= map(
    .configurations |= map(
        .dependencies |= map(update_dependencies)
    )
)