如何使用jq将bash数组添加到JSON数组的字段中? [英] How to add a bash array into the fields of a JSON array using jq?

查看:134
本文介绍了如何使用jq将bash数组添加到JSON数组的字段中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前从echo $items | jq获得以下JSON输出:

I currently have the following JSON output from echo $items | jq:

{
  "Family_Name": "Type 1",
  "Quantity_On_Hand": "335"
}
{
  "Family_Name": "Type 2",
  "Quantity_On_Hand": "215"
}
{
  "Family_Name": "Type 9",
  "Quantity_On_Hand": "159"
}
{
  "Family_Name": "Type 4",
  "Quantity_On_Hand": "500"
}

我也有一个大小相同的bash数组colors

I also have a bash array colors of the same size looking like

"Blue" "Red" "Green" "Blue"

如何使用jq以便获得类似的信息

How can I use jq so that I get something like

{
  "Family_Name": "Type 1",
  "Quantity_On_Hand": "335",
  "Colors": "Blue"
}
{
  "Family_Name": "Type 2",
  "Quantity_On_Hand": "215",
  "Colors": "Red"
}
{
  "Family_Name": "Type 9",
  "Quantity_On_Hand": "159",
  "Colors": "Green"
}
{
  "Family_Name": "Type 4",
  "Quantity_On_Hand": "500",
  "Colors": "Blue"
}

我尝试使用类似jq --argjq -n '.{} |= [$colors]'的方法,但无法正确使用.

I tried using something like jq --arg or jq -n '.{} |= [$colors]' but cannot get it correct.

推荐答案

使用jq 1.5或更高版本以及您的输入(即JSON对象流)和

Using jq 1.5 or later, with your input (i.e., a stream of JSON objects) and

colors=("Blue" "Red" "Green" "Blue")

下面的代码生成所需的JSON对象的数组:

the following produces an array of the desired JSON objects:

jq -s '
  ($ARGS.positional | map({Colors: .})) as $colors
  | [., $colors] | transpose | map(add)
' --args "${colors[@]}"

如果您希望结果是JSON对象的流,则可以添加[]或 将transpose | map(add)更改为transpose[] | add

If you want the result to be a stream of the JSON objects, you could tack on [] or change transpose | map(add) to transpose[] | add

(1)即使某些颜色的名称中有空格,上述解决方案也可以使用,但是通常可能需要使用其他某种机制来传递数组的内容.

(1) The above solution will work even if some colors have spaces in their names, but in general it may be necessary to pass in the contents of the array using some other mechanism.

(2)如果您的jq不支持位置参数(--args),那么现在可能是升级的好时机;如果这不是一种选择,则可以设计一种解决方法,例如如果您的jq支持,请使用--argfile选项.

(2) If your jq does not support positional parameters (--args), now may be a good time to upgrade; if that is not an option, you could devise a workaround, e.g. using the --argfile option if your jq supports that.

这篇关于如何使用jq将bash数组添加到JSON数组的字段中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆