Warm tip: This article is reproduced from stackoverflow.com, please click
json jq

Update field inside a nested JSON object based on key using jq

发布于 2020-03-27 10:28:10

I have a json file with the below format

{
    "l1":"",
    "values":{
        "id1":{
            "name":"abc",
            "enabled":"true"

        },
        "id2":{
            "name":"def",
            "enabled":"true"
        },
        "id3":{
            "name":"jjj"
        }
    }
}

I want to add/update the enabled status of the json object based on the parent key. so,eg: I have a file with below contents.

id1 false
id2 true
id3 false
id4 false

I want my output to look like below:

{
    "l1":"",
    "values":{
        "id1":{
            "name":"abc",
            "enabled":"false"

        },
        "id2":{
            "name":"def",
            "enabled":"true"
        },
        "id3":{
            "name":"jjj",
            "enabled":"false"
        }
    }
}

jq version:1.5

Questioner
dks551
Viewed
148
Jeff Mercado 2019-07-03 16:06

You can just create a mapping of the ids you want to update and the value to update to. Then use that mapping to update the corresponding values.

$ jq --argjson m '{"id1":"false","id2":"true","id3":"false","id4":"false"}' '
.values |= with_entries(.value.enabled = $m[.key])
' input.json