【问题标题】:How to pass bash array variable to jq not file如何将bash数组变量传递给jq而不是文件
【发布时间】:2021-12-14 13:26:34
【问题描述】:

我想修改我的 json 并添加更多字段

当前 JSON:

{
  "cubes": [
    {
      "no": 1,
      "plant_number": "1050-0"
    },
    {
      "no": 2,
      "plant_number": "2050-0"
    },
    {
      "no": 3,
      "plant_number": "3050-0"
    }
  ]
}

我想添加新字段,输出应该是这样的

预期输出:

{
  "no": 1,
  "plant_number": "1050-0",
  "1050-0":"1.1.1.1"
}
{
  "no": 2,
  "plant_number": "2050-0",
  "2050-0":"2.2.2.2"
}
{
  "no": 3,
  "plant_number": "3050-0",
  "3050-0":"3.3.3.3"
}

这些 IP 假设可以通过 bash 提取,所以我创建了类似的脚本

第一次尝试: 我可以像下面这样添加静态 ip

jq  '.cubes[]| {no,plant_number} | . + {(.plant_number): "0.0.0.0"} ' my.json 

它导致以下 JSON

{
  "no": 1,
  "plant_number": "1050-0",
  "1050-0","0.0.0.0"
}
{
  "no": 2,
  "plant_number": "2050-0",
  "2050-0":"0.0.0.0"
}
{
  "no": 3,
  "plant_number": "3050-0",
  "3050-0":"0.0.0.0"
}

第二次尝试:

# Here for sake of simplicity declaration is like this otherwise its function which return array
declare -a ips=('1.1.1.1' '2.2.2.2' '3.3.3.3');
jq  '.cubes[]| {no,plant_number} | . + {(.plant_number): $ips} ' my.json

给出错误

jq: 1 compile error

第三次尝试:

declare -a ips=('1.1.1.1' '2.2.2.2' '3.3.3.3');
jq  --arg ips $ips '.cubes[]| {no,plant_number} | . + {(.plant_number): $ips} ' my.json

这会导致以下结果

{
  "no": 1,
  "plant_number": "1050-0",
  "1050-0": "1.1.1.1 2.2.2.2 3.3.3.3"
}
{
  "no": 2,
  "plant_number": "2050-0",
  "2050-0": "1.1.1.1 2.2.2.2 3.3.3.3"
}
{
  "no": 3,
  "plant_number": "3050-0",
  "3050-0": "1.1.1.1 2.2.2.2 3.3.3.3"
}

如何为数组动态赋值?

【问题讨论】:

  • 预期输出不是有效的 JSON。
  • @choroba 对不起,我准备了 json,主要目的是添加带有 ip 的字段
  • 我假设你想要,例如,{"no": 1, "plant_number": "1050-0", "1050-0": "1.1.1.1"}?
  • @chepner 正确。

标签: bash jq


【解决方案1】:

你不能(轻易地)将一个数组从 shell 传递到 jq 中的一个数组中。但是当您处理(严格格式化的)IP 时,您可以将它们作为一个字符串 ("${ips[*]}") 传递,然后从 jq ($ips / " ") 中将其拆分为一个数组。

declare -a ips=('1.1.1.1' '2.2.2.2' '3.3.3.3');
jq --arg ips "${ips[*]}" '
  [.cubes, $ips / " "] | transpose[] as [$c,$ip] | $c + {($c.plant_number): $ip}
' my.json
{
  "no": 1,
  "plant_number": "1050-0",
  "1050-0": "1.1.1.1"
}
{
  "no": 2,
  "plant_number": "2050-0",
  "2050-0": "2.2.2.2"
}
{
  "no": 3,
  "plant_number": "3050-0",
  "3050-0": "3.3.3.3"
}

Demo

【讨论】:

    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 2015-05-21
    • 2021-05-25
    • 2018-04-16
    • 1970-01-01
    相关资源
    最近更新 更多