Am having a curl function to fetch data from webapi. the web API returns a Json String of format ["Name1","Name2","Name3","Name4","Name5"]
. I need to extract the data into an array in the bash script so that I could use the Names to loop in the rest of the code.
My required format is like arr[0]=Name1 ,...., arr[n]=Namen
Asked
Active
Viewed 314 times
-3

Cyrus
- 84,225
- 14
- 89
- 153

user3474213
- 43
- 5
-
1[Converting a JSON object into a Bash associative array](https://stackoverflow.com/q/26717277/608639), [How to convert string list to JSON string array in Bash?](https://stackoverflow.com/q/44477810/608639), etc. – jww Dec 31 '18 at 21:52
1 Answers
1
For elements without newlines you could do something as simple as this:
$ readarray -t arr < <(jq -r '.[]' <<< '["Name1","Name2"]')
$ declare -p arr
declare -a arr=([0]="Name1" [1]="Name2")
Reading this jq
request for NUL-delimited output, this will allow elements with newlines as well:
while IFS= read -rd '' item; do
arr+=("$item")
done < <(jq -j '.[]|(. + "\u0000")' <<< '["Name1","Na\nme2"]')
# with bash 4.4 or later
$ readarray -d '' arr < <(jq -j '.[]|(. + "\u0000")' <<< '["Name1","Na\nme2"]')
$ declare -p arr
declare -a arr=([0]="Name1" [1]=$'Na\nme2')

mickp
- 1,679
- 7
- 23
-
1+1. Possible improvement: If we *really* don't trust what the remote server is providing, you might consider making the latter remove any NUL literals from the incoming JSON so hostile values can't split themselves into new elements. That said, that's a tiny quibble, and I'm not sure I've always consistently done it myself in every answer I have here. – Charles Duffy Dec 31 '18 at 14:45