如何将Bash数组变量传递给jq而不是文件。

4

我希望修改我的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"
}

我如何动态地给数组分配值?


4
期望的输出不是一个有效的 JSON。 - choroba
@choroba 抱歉,我手动准备了JSON,主要意图是添加带有IP的字段。 - ImranRazaKhan
1
我猜你想要的是 {"no": 1, "plant_number": "1050-0", "1050-0": "1.1.1.1"} 这样的格式? - chepner
@chepner 正确。 - ImranRazaKhan
1个回答

2

您不能轻松地将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"
}

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接