Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Array of Objects from Bash Array using jq

Tags:

arrays

bash

jq

I am trying to create an array of objects in bash given an array in bash using jq.

Here is where I am stuck:

IDS=("baf3eca8-c4bd-4590-bf1f-9b1515d521ba" "ef2fa922-2038-445c-9d32-8c1f23511fe4")
echo "${IDS[@]}" | jq -R '[{id: ., names: ["bob", "sally"]}]'

Results in:

[
   {
     "id": "baf3eca8-c4bd-4590-bf1f-9b1515d521ba ef2fa922-2038-445c-9d32-8c1f23511fe4",
     "names": [
       "bob",
       "sally"
     ]
   }
]

My desired result:

[
   {
     "id": "baf3eca8-c4bd-4590-bf1f-9b1515d521ba",
     "names": [
       "bob",
       "sally"
     ]
   },
   {
     "id": "ef2fa922-2038-445c-9d32-8c1f23511fe4",
     "names": [
       "bob",
       "sally"
     ]
   }
]

Any help would be much appreciated.

like image 655
Jghorton14 Avatar asked Nov 19 '25 04:11

Jghorton14


2 Answers

Split your bash array into NUL-delimited items using printf '%s\0', then read the raw stream using -R or --raw-input and within your jq filter split them into an array using split and the delimiter "\u0000":

printf '%s\0' "${IDS[@]}" | jq -Rs '
  split("\u0000") | map({id:., names: ["bob", "sally"]})
'
like image 66
pmf Avatar answered Nov 20 '25 17:11

pmf


for id in "${IDS[@]}" ; do
  echo "$id"
done | jq -nR '[ {id: inputs, names: ["bob", "sally"]} ]'

or as a one-liner:

printf "%s\n" "${IDS[@]}" | jq -nR '[{id: inputs, names: ["bob", "sally"]}]'
like image 34
peak Avatar answered Nov 20 '25 18:11

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!