How to add a bash array into the fields of a JSON array using jq?

回眸只為那壹抹淺笑 提交于 2021-02-10 15:46:58

问题


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"
}

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

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

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"
}

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


回答1:


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

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

the following produces an array of the desired JSON objects:

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

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

Caveats

(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) 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.




回答2:


Here's a solution that has been tested with versions of jq from 1.4 onwards:

jq -R -s --argfile json <(echo "$items") '
  (split("\n") | map(select(length>0))) as $colors
  | [ range(0; $colors|length) | $json[.] + {Colors: $colors[.]} ]
' <( printf "%s\n" "${colors[@]}" )

The subtlety here is that -argfile will combine the stream of JSON objects into a single array.



来源:https://stackoverflow.com/questions/64623254/how-to-add-a-bash-array-into-the-fields-of-a-json-array-using-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!