简体   繁体   中英

How do I add parent keys in jq

I want to promote a value from inside an array element to be the parent key for the entire element.

Input:

[
    {
        "name": "foo",
        "value1": "fooval1",
        "value2": "fooval2"
    },
    {
        "name": "bar",
        "value1": "barval1",
        "value2": "barval2"
    }
]

Output:

{
    "foo":{
        "value1": "fooval1",
        "value2": "fooval2"
    },
    "bar":{
        "value1": "barval1",
        "value2": "barval2"
    }
}

To start with, I wanted to just add .name as a parent key to each entry. But this doesnt' work:

jq 'map(.name: {.})'

How do I add parent keys ?

Easily, at least once the syntax errors in the input file have been fixed. The key is to wrap parentheses around .name to form the new key:

map( {(.name): del(.name)} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM