Notification texts go here Contact Us Buy Now!

Build a JSON string with Bash variables

```html

<!DOCTYPE html>
<html>
<head>
<title>Build a JSON string with Bash variables</title>
</head>
<body>

<p>First, don't use ALL_CAPS_VARNAMES: it's too easy to accidentally overwrite a crucial shell variable (like PATH).</p>

<p>Mixing single and double quotes in shell strings can be a hassle. In this case, I'd use printf:</p>

<pre>bucket_name=testbucket
object_name=testworkflow-2.0.1.jar
target_location=/opt/test/testworkflow-2.0.1.jar
template='{"bucketname":"%s","objectname":"%s","targetlocation":"%s"}'

json_string=$(printf "$template" "$BUCKET_NAME" "$OBJECT_NAME" "$TARGET_LOCATION")

echo "$json_string"
</pre>

<p>For homework, read this page carefully: <a href="https://unix.stackexchange.com/q/171346/4667" target="_blank">Security implications of forgetting to quote a variable in bash/POSIX shells</a></p>

<hr>

<p>A note on creating JSON with string concatenation: there are edge cases. For example, if any of your strings contain double quotes, you can broken JSON:</p>

<pre>$ bucket_name='a "string with quotes"'
$ printf '{"bucket":"%s"}\n' "$bucket_name"
{"bucket":"a "string with quotes""}
</pre>

<p>Do do this more safely with bash, we need to escape that string's double quotes:</p>

<pre>$ printf '{"bucket":"%s"}\n' "${bucket_name//\"/\\\"}"
{"bucket":"a \"string with quotes\""}
</pre>

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.