Skip to content

Instantly share code, notes, and snippets.

@ORESoftware
Last active April 22, 2018 06:49
Show Gist options
  • Save ORESoftware/a4e3948b0ce9c22752c759d7e694c9ab to your computer and use it in GitHub Desktop.
Save ORESoftware/a4e3948b0ce9c22752c759d7e694c9ab to your computer and use it in GitHub Desktop.
Convert array to JSON in Bash shell
#!/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
@ORESoftware
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment