3

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.

2 Answers 2

5

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"]})
'
Sign up to request clarification or add additional context in comments.

6 Comments

What is the purpose of null in this context?
@dan null cannot occur in C-strings, or anything that mimics them; therefore, they tend to be safe to use as delimiters. (As opposed to spaces, newlines, etc which sometimes do occur in the middle of normalish strings.) In this case, it looks like the strings are pretty plain, so newlines are probably safe enough, but that's not always true.
@GordonDavisson That’s true, however I tried this example with a bash array that had a multiline element, and everything was still split on new lines. With the accepted answer, it was split in to objects ({ }), and using nulls it was split in to arrays ([ ]).
@dan Can you provide your "bash array that had a multiline element" and how you created it?
@dan You are right, I forgot to --slurp the input. Fixed it.
|
2
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"]}]'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.