Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a bash array as a JSON array

Tags:

json

arrays

bash

jq

I have a bash array

X=("hello world" "goodnight moon")

That I want to turn into a json array

["hello world", "goodnight moon"]

Is there a good way for me to turn this into a json array of strings without looping over the keys in a subshell?

(for x in "${X[@]}"; do; echo $x | sed 's|.*|"&"|'; done) | jq -s '.'

This clearly doesn't work

echo "${X[@]}" | jq -s -R '.'
like image 461
Jon Avatar asked Nov 07 '14 19:11

Jon


People also ask

How do I convert an array to JSON?

You convert the whole array to JSON as one object by calling JSON. stringify() on the array, which results in a single JSON string. To convert back to an array from JSON, you'd call JSON. parse() on the string, leaving you with the original array.

What is the difference between {} and [] in JSON?

{} denote containers, [] denote arrays.

What are {} in JSON?

JSON has the following syntax. Objects are enclosed in braces ( {} ), their name-value pairs are separated by a comma ( , ), and the name and value in a pair are separated by a colon ( : ). Names in an object are strings, whereas values may be of any of the seven value types, including another object or an array.


2 Answers

You can do this:

X=("hello world" "goodnight moon")
printf '%s\n' "${X[@]}" | jq -R . | jq -s .

output

[
  "hello world",
  "goodnight moon"
]
like image 128
kev Avatar answered Sep 29 '22 02:09

kev


This ...

X=("hello world" "goodnight moon" 'say "boo"' 'foo\bar')

json_array() {
  echo -n '['
  while [ $# -gt 0 ]; do
    x=${1//\\/\\\\}
    echo -n \"${x//\"/\\\"}\"
    [ $# -gt 1 ] && echo -n ', '
    shift
  done
  echo ']'
}

json_array "${X[@]}"

... yields:

["hello world", "goodnight moon", "say \"boo\"", "foo\\bar"]

If you are planning to do a lot of this (as your reluctance to use a subshell suggests) then something such as this that does not rely on any subprocess is likely to your advantage.

like image 40
John Bollinger Avatar answered Sep 29 '22 02:09

John Bollinger