如何使用 jq 更新 json 文件中的子项?

How to update a subitem in a json file using jq?

使用 jq 我尝试更新此 json 文档:

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

moduleF 添加到 NamespaceY。我需要将文件再次写回原始源文件。

我接近(但没有雪茄):

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

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

以下过滤器应该执行您想要的更新:

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

注意开头的'.|'在您的尝试中不需要; "NamespaceY" 在 config.json 中大写;如图所示的 parens 是成功的关键;并且 += 可以在这里使用。

一种写回原始文件的方法可能是使用 'sponge'; jq 常见问题 https://github.com/stedolan/jq/wiki/FAQ

上讨论了其他可能性