【问题标题】:jq command to replace array value with non-json valuejq命令用非json值替换数组值
【发布时间】: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'吗?

标签: json templates jinja2 jq


【解决方案1】:

实现仅 jq 的解决方案是不切实际的,但 jq 肯定可以提供帮助,例如以下适用于您的情况:

jq '.clients[] |= (.webOrigins = "{{clients.\(.clientId).webOrigins}}")' |
    sed '/"webOrigins":/ { s/"[{][{]/{{/; s/[}][}]"$/}}/; }'

【讨论】:

  • 我认为您可以省略正则表达式中每个大括号周围的[...]sed 可以通过上下文判断它们不是绑定的一部分。
  • 我最终选择了类似的东西。
猜你喜欢
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多