I have utility which accept JSON as argument. How to escape json correctly to pass to the utility? Example:
ip="127.0.0.1"
action='{\"server_ip\":\"$ip\",\"action\":\"stop\"}'
./fix-utility -e $action
But JSON is not getting escaped correctly.
If you want interpolation of e.g. $ip
inside the string, you need to use double quotes. Double quotes in the value need backslash escaping.
ip="127.0.0.1"
action="{\"server_ip\":\"$ip\",\"action\":\"stop\"}"
./fix-utility -e "$action"
Actually, I would advise against storing the action in a variable, unless your example omits something crucial which makes it necessary.
Double quotes and single quotes is not considered same by bash interpreter: While double-quote let bash expand contained variables, single quote don't. Try simply:
echo "$BASH_VERSION"
4.1.5(1)-release
echo '$BASH_VERSION'
$BASH_VERSION
At all, there is a nice reusable bash way:
declare -A jsonVar
toJsonString() {
local string='{'
for var in ${!jsonVar[*]} ;do
string+="\"$var\":\"${jsonVar[$var]}\","
done
echo ${string%,}"}"
}
jsonVar[action]=stop
jsonVar[server_ip]=127.0.1.2
toJsonString
{"action":"stop","server_ip":"127.0.1.2"}
And finally:
./fix-utility -e "$(toJsonString)"
This could be improved if specials chars like "
double-quotes have to be part of some strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With