【发布时间】:2020-03-13 09:19:22
【问题描述】:
我需要一个 jq 命令来用非 json 标准值替换数组值,即在下面的 json 输入中,我需要用非 json 值替换“webOrigins”数组值,这是一个 Jinja2 模板变量替换下面的第二个 json 块。
输入 (example.json)
{
"clients": [
{
"clientId": "abc",
"webOrigins": [ "/", "/api" ]
},
{
"clientId": "xyz",
"webOrigins": [ ]
}
]
}
期望的输出
{
"clients": [
{
"clientId": "abc",
"webOrigins": {{clients.abc.webOrigins}}
},
{
"clientId": "xyz",
"webOrigins": {{clients.xyz.webOrigins}}
}
]
}
我目前调用 jq 的 shell 脚本循环输入 json 并用模板变量替换的尝试是这样的
for clientId in $(jq -r '.clients[] | .clientId' example.json)
do
jq '(.clients[] | select(.clientId == "'${clientId}'") | .webOrigins) |= {{ clients['\'${clientId}\''].webOrigins | default([]) }}' example.json > tmp.j2; mv -f tmp.j2 example.json
done
但因错误而失败:
jq: error: syntax error, unexpected '{' (Unix shell quoting issues?) at <top-level>, line 1:
(.clients[] | select(.clientId == "abc") | .webOrigins) |= {{ clients['abc'].webOrigins | default([]) }}
jq: 1 compile error
当然,如果我在模板变量周围添加双引号以使替换变量有效 json,则脚本可以工作,但我需要该值没有引号。
【问题讨论】:
-
会喜欢
jq '.clients[].webOrigins = ""' file | sed 's/""/{{clients.abc.webOrigins}}/g'吗?