问题
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