使用 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 中大写;如图所示的 parent 是成功的关键; += 可以在这里使用。
写回原始文件的一种方法可能是使用“海绵”;其他可能性在 jq 常见问题解答 https://github.com/stedolan/jq/wiki/FAQ 中讨论
关于json - 如何使用 jq 更新 json 文件中的子项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43180340/