Skip to content

Instantly share code, notes, and snippets.

@hilbix
Last active February 27, 2024 22:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hilbix/c75ac2a63758dc8410d7 to your computer and use it in GitHub Desktop.
Save hilbix/c75ac2a63758dc8410d7 to your computer and use it in GitHub Desktop.
Parse JSON into BASH variables, with onedimensional array support
#!/bin/bash
#
# A slightly more secure variant of this script.
# It should be secure against primitive attacks like:
json2bash <<<'{" ":{"; rm -rf /; ":1}}'
#
# However processing JSON from untrustworthy sources still can confuse your script!
# YOU HAVE BEEN WARNED!
# Following needs bash. Use like in:
# eval "$(json2bash <<<"$JSONDATA")"
# JSONDATA must be coming from a trustworthy source, else harm may arise!
json2bash()
{
# This only supports a single array output, as multidimensional arrays are not supported
# -MJSON needs libjson-perl under Debian
# STDIN must be from a trustworthy source!
perl -MJSON -0777 -n -E 'sub J {
my ($p,$v) = @_; my $r = ref $v;
if ($r eq "HASH") { tr/-A-Za-z0-9_//cd, J("${p}_$_", $v->{$_}) for keys %$v; }
elsif ($r eq "ARRAY") { $n = 0; J("$p"."[".$n++."]", $_) foreach @$v; }
else { $v =~ '"s/'/'\\\\''/g"'; $p =~ s/^([^[]*)\[([0-9]*)\](.+)$/$1$3\[$2\]/;
$p =~ tr/-/_/; $p =~ tr/A-Za-z0-9_[]//cd; say "$p='\''$v'\'';"; }
}; J("json", decode_json($_));'
}
# Examples
json2bash <<<'["a","b","c"]'
# outputs:
#json[0]='a';
#json[1]='b';
#json[2]='c';
json2bash <<<'{"keys":["a","b","c"],"values":["c"]}'
# outputs (not neccessarily in this order):
#json_values[0]='c';
#json_keys[0]='a';
#json_keys[1]='b';
#json_keys[2]='c';
json2bash <<<'[{"a":"1"},{"a":"2"},{"a":3}]'
# outputs (not as you expect json[0]_a .. json[1]_a ..):
#json_a[0]='1';
#json_a[1]='2';
#json_a[2]='3';
json2bash <<<'[["a","b"],["c","d"]]'
# is NOT supported and produces following garbage:
#json[0][0]='a';
#json[1][0]='b';
#json[0][2]='c';
#json[1][2]='d';
@hilbix
Copy link
Author

hilbix commented Mar 22, 2018

Perhaps have a look at json2sh

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