Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save awesome/b3f65084c70264e87be3e72ee8abd0e5 to your computer and use it in GitHub Desktop.
Save awesome/b3f65084c70264e87be3e72ee8abd0e5 to your computer and use it in GitHub Desktop.
jq parse JSON to bash4 associative array! "jq is like sed for JSON data" https://stedolan.github.io/jq/
admin@ip-172-31-90-86:~$ json=$(
cat <<- EOF
{
"foo": "baru-1",
"su": "baru-2",
"dive": "baru-3"
}
EOF
)
admin@ip-172-31-90-86:~$ echo $json
{ "foo": "baru-1", "su": "baru-2", "dive": "baru-3" }
admin@ip-172-31-90-86:~$ arrayAsString=$(echo $json | jq --raw-output '. | to_entries | map("[\(.key)]=\(.value)") | reduce .[] as $item ("associativeArray=("; . + $item + " ") + ")"')
admin@ip-172-31-90-86:~$ echo $arrayAsString
associativeArray=([dive]=baru-3 [foo]=baru-1 [su]=baru-2 )
admin@ip-172-31-90-86:~$ declare -A "$arrayAsString"
admin@ip-172-31-90-86:~$ echo ${associativeArray[foo]}
baru-1
admin@ip-172-31-90-86:~$ echo ${associativeArray[su]}
baru-2
admin@ip-172-31-90-86:~$ echo ${associativeArray[dive]}
baru-3
admin@ip-172-31-90-86:~$ jq
jq - commandline JSON processor [version 1.4-1-e73951f]
Usage: jq [options] <jq filter> [file...]
For a description of the command line options and
how to write jq filters (and why you might want to)
see the jq manpage, or the online documentation at
http://stedolan.github.com/jq
admin@ip-172-31-90-86:~$ /bin/bash --version
GNU bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
admin@ip-172-31-90-86:~$ ec2metadata
ami-id: ami-b14ba7a7
##
# "Piping … JSON into JQ"
# https://stackoverflow.com/questions/26717277/converting-a-json-object-into-a-bash-associative-array#51690860
# `declare -A` only works in bash4
#
json=$(
cat <<- EOF
{
"foo": "baru-1",
"su": "baru-2",
"dive": "baru-3"
}
EOF
)
arrayAsString=$(echo $json | jq --raw-output '. | to_entries | map("[\(.key)]=\(.value)") | reduce .[] as $item ("associativeArray=("; . + $item + " ") + ")"')
declare -A "$arrayAsString"
#echo ${associativeArray[foo]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment