How to use `jq` to convert a json by combine some of the values?

107 views Asked by At

Say I have a 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"
                        }
                    ]
                }
            ]
        }
        ]
    }
    ]
}

How can I use jq to convert the JSON to:

{
    "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

There are 1 answers

0
Jeff Mercado On BEST ANSWER

With a help of a function, you can do this recursively.

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