Last active
April 22, 2018 06:49
-
-
Save ORESoftware/a4e3948b0ce9c22752c759d7e694c9ab to your computer and use it in GitHub Desktop.
Convert array to JSON in Bash shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
ql_join_arry_to_json(){ | |
local arr=( "$@" ); | |
local len=${#arr[@]} | |
if [[ ${len} -eq 0 ]]; then | |
>&2 echo "Error: Length of input array needs to be at least 2."; | |
return 1; | |
fi | |
if [[ $((len%2)) -eq 1 ]]; then | |
>&2 echo "Error: Length of input array needs to be even (key/value pairs)."; | |
return 1; | |
fi | |
local data=""; | |
local foo=0; | |
for i in "${arr[@]}"; do | |
local char="," | |
if [ $((++foo%2)) -eq 0 ]; then | |
char=":"; | |
fi | |
local first="${i:0:1}"; # read first charc | |
local app="\"$i\"" | |
if [[ "$first" == "^" ]]; then | |
app="${i:1}" # remove first char | |
fi | |
data="$data$char$app"; | |
done | |
data="${data:1}"; # remove first char | |
echo "{$data}"; # add braces around the string | |
} | |
#### now use it like so: | |
$ ql_join_arry_to_json a 3 c true | |
# => {"a":"3","c":"true"} | |
# but wait, what about numbers and booleans? | |
ql_join_arry_to_json a ^3 c ^true | |
# => {"a":3,"c":true} | |
# that should work, let me know if there are some broken edge cases...lulz | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or just use here-doc, which is probably easier:
https://stackoverflow.com/questions/43373176/store-json-directly-in-bash-script-with-variables