1

New to jq here.

I just want to ask how to add the key of an object to each item of its value and convert it to an array of objects instead. I have the following JSON format:

{
    "key1" : [
        "key1item1",
        "key1item2",
        "key1item3",
        "key1item4",
        ...
    ],
    "key2" : [
        "key2item1",
        "key2item2",
        ...
    ]
}

What I want to achieve is this:

{
    "key1" : [
        {
            'parent': 'key1',
            'key': 'key1_key1item1',
            'value': 'key1_item1',
        },
        {
            'parent': 'key1',
            'key': 'key1_key1item2',
            'value': 'key1_item2',
        }
        {
            'parent': 'key1',
            'key': 'key1_key1item3',
            'value': 'key1_item3',
        }
    ],
    "key2" : [
        {
            'parent': 'key2',
            'key': 'key2_key2item1',
            'value': 'key2_item1',
        },
        {
            'parent': 'key2',
            'key': 'key2_key2item2',
            'value': 'key2_item2',
        }
        {
            'parent': 'key2',
            'key': 'key2_key2item3',
            'value': 'key2_item3',
        }
    ]

1 Answer 1

1

This should do it:

with_entries(
    .key as $key
    | .value |= map(
         {parent: $key,
          key: ($key + (tostring)), 
          value: .}) )
Sign up to request clarification or add additional context in comments.

Comments

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.