jq:将嵌套对象添加到JSON [英] jq: adding nested object to a JSON
问题描述
我有一个包含多个配置文件的json文件:
I have a json file containing several profiles:
{
"profile1": {
"user": "user1",
"channel": "channel1",
"hook": "hook1"
},
"default": {
"user": "user1",
"channel": "channel1",
"hook": "hook2"
}
}
我想使用jq插入另一个配置文件测试",以便最终结果为
I want to use jq to insert another profile, "test", so that the end result will be
{
"profile1": {
"user": "user1",
"channel": "channel1",
"hook": "hook1"
},
"default": {
"user": "user1",
"channel": "channel1",
"hook": "hook2"
},
"test": {
"user": "user3",
"channel": "channel3",
"hook": "hook3"
}
}
我可以直接在命令行中执行以下操作:
Directly in the command line I can do it with:
cat filename |
jq '.+ { "test": { "user": "u3", "channel" : "c3", "hook": "w3" } }'
但是当我在bash脚本中尝试时:
But when I try it in my bash script:
cat "$CONF_FILE" |
jq --arg p "$PROFILE" --arg u "$U" --arg c "$C" --arg w "$WH" \
'.+ { $p: { "user": $u, "channel": $c, "hook": $w } }' `
我遇到以下错误:
jq: error: syntax error, unexpected ':', expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
.+ { $p: { "user": $u, "channel": $c, "hook": $w } }
jq: error: syntax error, unexpected '}', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.+ { $p: { "user": $u, "channel": $c, "hook": $w } }
jq: 2 compile errors
我尝试用引号将变量引起来,但随后我只得到字符串$ p:
I've tried surrounding the variable with quotes but then I get just the string $p:
cat "$CONF_FILE" |
jq --arg p "$PROFILE" --arg u "$U" --arg c "$C" --arg w "$WH" \
'.+ { "$p": { "user": $u, "channel": $c, "hook": $w } }'
结果:
{
"profile1": {
"user": "user1",
"channel": "channel1",
"hook": "hook1"
},
"default": {
"user": "user1",
"channel": "channel1",
"hook": "hook2"
},
"$p": {
"user": "user3",
"channel": "channel3",
"hook": "hook3"
}
}
编辑:我发现了一种临时解决方案,将对象转换为数组,编辑值(现在的配置文件名称是值而不是键),然后将数组转换回一个对象:
I have found what seems a temporary solution, converting the object to an array, editing the value (now the profile name is a value and not a key) and converting the array back to an object:
cat "$CONF_FILE" |
jq --arg p "$PROFILE" --arg u "$U" --arg c "$C" --arg w "$WH" \
'to_entries | .+ [ { "key": $p, "value": { "user": $u, "channel": $c, "hook": $w } } ] | from_entries'
这似乎很粗糙,但确实有效.我仍然希望有一个更好的解决方案...
It seems crude, but it works. I am still hoping for a better solution...
推荐答案
在动态键周围使用括号:
Use parenthesis around dynamic keys:
jq --arg p "$PROFILE" --arg u "$U" --arg c "$C" --arg w "$WH" \
'. + {($p): {"user": $u, "channel": $c, "hook": $w}}' "$CONF_FILE"
这篇关于jq:将嵌套对象添加到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!