Home > Enterprise >  Creating Array of Objects from Bash Array using jq
Creating Array of Objects from Bash Array using jq

Time:11-05

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.

CodePudding user response:

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 -R '
  split("\u0000") | map({id:., names: ["bob", "sally"]})
'

CodePudding user response:

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"]}]'
  • Related