Skip to content

Instantly share code, notes, and snippets.

@skywarth
Created July 26, 2021 20:56
Show Gist options
  • Save skywarth/0dea4a1b3ccce8320b7f6eb595553598 to your computer and use it in GitHub Desktop.
Save skywarth/0dea4a1b3ccce8320b7f6eb595553598 to your computer and use it in GitHub Desktop.
Bash parse json as associative array (recursive). Supports integer and floating point values too.
Toolbelt_parseJSON(){
local -n jsonArray=$2
jsonArray[0]="rrr"
SETTINGS_FILE="$1"
SETTINGS_JSON=$(cat $SETTINGS_FILE)
__readJSON "$SETTINGS_JSON"
}
# Usage:
# declare -A firstJSON #this is an array
# declare -A secondJSON #this is an array
# Toolbelt_parseJSON "./test.json" firstJSON
# Toolbelt_parseJSON "./test2.json" secondJSON
# echo "--"
# echo "${firstJSON[@]}"
# echo "${secondJSON[@]}"
__readJSON() {
local JSON=`jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" <<< "$1"`
local KEYS=''
if [ $# -gt 1 ]; then
KEYS="$2"
fi
while read -r PAIR; do
local KEY=''
if [ -z "$PAIR" ]; then
break
fi
IFS== read PAIR_KEY PAIR_VALUE <<< "$PAIR"
if [ -z "$KEYS" ]; then
KEY="$PAIR_KEY"
else
KEY="$KEYS:$PAIR_KEY"
fi
res=$(jq -e . 2>/dev/null <<< "$PAIR_VALUE")
exitCode=$?
check=`echo "$PAIR_VALUE" | grep -E ^\-?[0-9]*\.?[0-9]+$`
# if [ "${res}" ] && [ $exitCode -eq "0" ] && [[ ! "${PAIR_VALUE}" == ?(-)+([0-9]) ]] ALTERNATIVE, works only for integer (not floating point)
if [ "${res}" ] && [ $exitCode -eq "0" ] && [[ "$check" == '' ]]
then
__readJSON "$PAIR_VALUE" "$KEY"
else
jsonArray["$KEY"]="$PAIR_VALUE"
fi
done <<< "$JSON"
}
# Example as below:
#declare -A firstJSON
#declare -A secondJSON
#Toolbelt_parseJSON "./test.json" firstJSON
#Toolbelt_parseJSON "./test2.json" secondJSON
#echo "--"
#echo "${!firstJSON[@]}"
#echo "${secondJSON[@]}"
#echo "${firstJSON[web-app:servlet-mapping:cofaxEmail]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment