How do I update a subitem in a json file using jq?

Using jq

, I tried to update this json document:

{
"git_defaults": {
    "branch": "master",
    "email": "jenkins@host",
    "user": "Jenkins"
},
"git_namespaces": [
{
    "name": "NamespaceX",
        "modules": [
            "moduleA",
            "moduleB",
            "moduleC",
            "moduleD"
        ]
},
{
    "name": "NamespaceY",
    "modules": [
        "moduleE"
    ]
}
]
}

      

with the addition moduleF

to NamespaceY

. I need to write the file back to the original file again.

I came close (but not a cigar) with:

jq  '. | .git_namespaces[] | select(.name=="namespaceY").modules |= (.+ ["moduleF"])' config.json

      

and

jq '. | select(.git_namespaces[].name=="namespaceY").modules |= (.+ ["moduleF"])' config.json

      

+3


source to share


1 answer


The following filter should perform the required update:

(.git_namespaces[] | select(.name=="NamespaceY").modules) += ["moduleF"]

      



Please note that the initial '. | ' in your attempt it is not required; that "Namespace" is capitalized in config.json; that paranas have been shown to be the keys to success; and that you can use + = here.

One way to write back to the original file, perhaps, would be to use a sponge; other possibilities are discussed on the jq FAQ https://github.com/stedolan/jq/wiki/FAQ

+1


source







All Articles