给定测试文件:sample.json:
{
"host_config": {
"host1.reg.fqdn.com": {
"config1": "AAA",
"config2": "000"
},
"host2.reg.fqdn.com": {
"config1": "BBB",
"config2": "000"
},
"host3.reg.fqdn.com": {
"config1": "CCC",
"config2": "000"
}
}
}
我需要为每个主机名键更新“config2”,但我似乎无法使用主机名的 --arg var 定义格式获得正确的 jq 语法。 (使用jq1.6)
jq '.host_config."host1.reg.fqdn.com".config2=1' sample.json good!
jq --arg a "1" '.host_config."host1.reg.fqdn.com".config2=$a' sample.json good!
jq --arg a "1" --arg b "host1.reg.fqdn.com" '.host_config."$b".config2=$a' sample.json
completes but does not sub in "host1.reg.fqdn.com" for b - it creates new key under .host_config like:
"$b": {
"config2": "1"
}
jq --arg a "1" --arg b "host1.reg.fqdn.com" '.host_config.'$b'.config2=$a' sample.json =\> jq error
jq --arg a "1" --arg b "host1.reg.fqdn.com" '.host_config.[$b].config2=$a' sample.json =\> jq error
jq --arg a "1" --arg b "host1.reg.fqdn.com" '.host_config.['$b'].config2=$a' sample.json =\> jq error
jq --arg a "1" --arg b "host1.reg.fqdn.com" '.host_config.["$b"].config2=$a' sample.json =\> jq error
jq --arg a "1" --arg b "host1.reg.fqdn.com" '.host_config.'"$b"'.config2=$a' sample.json =\> jq error
jq --arg a "1" --arg b "host1.reg.fqdn.com" '.host_config."'$b'".config2=$a' sample.json =\> completes but
creates:
"": {
"config2": "1"
}
最终我想做的是:
for i in 1..3 ; do
jq --arg a "$i" --arg b "host${i}.reg.fqdn.com" '.host_config."$b".config2=$a' sample.json
done
.host_config."$b".config2
包含文字键
$b
并且不会被插值,就像 "$a"
是包含美元和字母“a”的字符串文字一样。要从变量值获取键名称,请使用括号:
.host_config[$b].config2