bash - 在 bash 中将数组变量传递给 jq

标签 bash jq

是否可以在 jq 中传递和使用数组类型的变量?

jq --arg ips "${IPs[0]}" '.nodes.app.ip = $ips[0] | .nodes.data.ip = $ips[1]' nodes.json

最佳答案

一般情况下的解决方案是使用 NUL 分隔符在 stdin 上传递该数组:

IPs=( 1.2.3.4 5.6.7.8 )
original_doc='{"nodes": { "app": {}, "data": {} }}'

jq -Rn --argjson original_doc "$original_doc" '
  input | split("\u0000") as $ips
  | $original_doc
  | .nodes.app.ip = $ips[0]
  | .nodes.data.ip = $ips[1]
' < <(printf '%s\0' "${IPs[@]}")

...作为输出发出:

{
  "nodes": {
    "app": {
      "ip": "1.2.3.4"
    },
    "data": {
      "ip": "5.6.7.8"
    }
  }
}

这对于 IP 地址数组来说有点过分了,但它在一般情况下都有效,即使对于主动敌对的数组(带有文字引号、文字换行符和其他故意难以解析的数据的数组)也是如此。


如果您想保持 stdin 干净,可以使用 jq 的第二个副本将数组转换为 JSON:

IPs=( 1.2.3.4 5.6.7.8 )
IPs_json=$(jq -Rns 'input | split("\u0000")' < <(printf '%s\0' "${IPs[@]}"))

jq --argjson ips "$IPs_json" '
    .nodes.app.ip = $ips[0]
  | .nodes.data.ip = $ips[1]
' <<<'{"nodes": { "app": {}, "data": {} }}'

关于bash - 在 bash 中将数组变量传递给 jq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58399373/

相关文章:

python - 将许多JSON对象索引到Elasticsearch中-规范方法

linux - 带有单引号 bash 脚本的 jq

json - 使用 jq 和 awk 拆分大型 JSON 文件

json - 将平面 JSON 转换为按公共(public)键名分组的嵌套 JSON

linux - 用于从文件创建数组并在 curl URL 上使用每个值的 Bash 脚本

mysql - 将从站状态\G 显示到输出文件 '/tmp/slavestatus.txt' 中;

bash - 如果函数位于子 shell 内,其行为会如何变化?

导入模块(并选择正确的解释器)的 Python shebang 问题

python - 如何在 python 中使用来自 bash 的数据流和子进程

json - 使用 jq 展平 json 对象