I've got a JSON list (the value of a key-value pair containing a list of items):
[ "john", "boris", "joe", "frank" ]
How would I convert this to a bash array, so I can iterate over them?
I've got a JSON list (the value of a key-value pair containing a list of items):
[ "john", "boris", "joe", "frank" ]
How would I convert this to a bash array, so I can iterate over them?
Easy Case: Newline-Free Strings
The simple approach is to use
jq
to transform your list into a line-per-item, and read that into your script:...properly emits:
Tricky Case: Strings With Newlines
Sometimes you need to read strings that can contain newlines (or want to avoid security risks caused by malicious or malformed data being read into the wrong fields). To avoid that, you can use NUL delimiters between your data (and remove any NUL values contained therein):
...properly emits:
...and
printf '<%s>\n\n' "${array[@]}"
properly emits:(Note that very new bash has
readarray -0
, which can avoid the need for thewhile IFS= read -r -d ''
loop given above, but that's not common yet. Also note that you can use that loop to directly iterate over content fromjq
, avoiding the need to store content in an array in the first place; see BashFAQ #1).