0

I would like to map the following structure

{
    "id" : "OUTER_ID",
    "name" : "OUTER_NAME"
    "items" : [ 
        {   
            "id" : "INNER_ID_1",
            "name" : "INNER_NAME_1",
        },
        {   
            "id" : "INNER_ID_2",
            "name" : "INNER_NAME_2",
        }
    ]   
}

into this

{
    "payload": [
        {   
            "key" : "INNER_NAME_1_KEY",
            "data" : { 
                "id" : "OUTER_ID",
                "name" : "OUTER_NAME",
                "items" : [ 
                    {   
                        "id" : "INNER_ID_1",
                        "name" : "INNER_NAME_1"
                    }   
                ]   
            }   
        },  
        {   
            "key" : "INNER_NAME_2_KEY",
            "data" : { 
                "id" : "OUTER_ID",
                "name" : "OUTER_NAME",
                "items" : [ 
                    {
                        "id" : "INNER_ID_2",
                        "name" : "INNER_NAME_2"
                    }
                ]
            }
        }
    ]
}

So, for each item in the initial items array, I want to create an entry in the output's payload, i.e I want to map items[i] to payload[i].data.items while also creating the payload, key and data keys in the output, and setting payload[i].data.id and payload[i].data.name to the input's outer id and name.

Can this be done with jq?

1 Answer 1

3

Sure, you can use the following filter :

.id as $id | .name as $name | {payload : [ .items[] | {key:.id, data:{id:$id, name: $name, items:[.]}} ] }

You can try it here.

Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.