Build a JSON string with Bash variables

bash json variable
jq bash
bash string to json
bash multiline string
bash script to read values from json file
bash json variable substitution
jq create json
bash parse json

I need to read these bash variables into my JSON string and I am not familiar with bash. any help is appreciated.

#!/bin/sh

BUCKET_NAME=testbucket
OBJECT_NAME=testworkflow-2.0.1.jar
TARGET_LOCATION=/opt/test/testworkflow-2.0.1.jar

JSON_STRING='{"bucketname":"$BUCKET_NAME"","objectname":"$OBJECT_NAME","targetlocation":"$TARGET_LOCATION"}'


echo $JSON_STRING 

You are better off using a program like jq to generate the JSON, if you don't know ahead of time if the contents of the variables are properly escaped for inclusion in JSON. Otherwise, you will just end up with invalid JSON for your trouble.

BUCKET_NAME=testbucket
OBJECT_NAME=testworkflow-2.0.1.jar
TARGET_LOCATION=/opt/test/testworkflow-2.0.1.jar

JSON_STRING=$( jq -n \
                  --arg bn "$BUCKET_NAME" \
                  --arg on "$OBJECT_NAME" \
                  --arg tl "$TARGET_LOCATION" \
                  '{bucketname: $bn, objectname: $on, targetlocation: $tl}' )

Bash variable substitution in a JSON string, JSON=\''{"hostname": "localhost", "outdir": "'"$OUTDIR"'", "port": 20400, "size": 100000}'\'. That is get out of the single quotes for the expansion of $OUTDIR . That’s tough to read and even tougher to write. You have to pipe to 4 different utilities just to get to a property in the JSON response body! Bash doesn’t understand JSON out of the box, and using the typical text manipulation tools like grep, sed, or awk, gets difficult. Luckily there’s a better way using a tool called jq.

You can use printf:

JSON_FMT='{"bucketname":"%s","objectname":"%s","targetlocation":"%s"}\n'
printf "$JSON_FMT" "$BUCKET_NAME" "$OBJECT_NAME" "$TARGET_LOCATION"

much clear and simpler

Working with JSON in bash using jq, jq is a powerful tool that lets you read, filter, and write JSON in bash. By making JSON easy to work with in bash, jq opens up a lot of automation possibilities that params: $1 = the string to grep for, $2 = directory to grep in. Notice that the JSON string for the newline character is " " (not "\ "). A third case of interest is when VAR is a bash array. In this case, it may be acceptable to pass in the items using "${VAR[@]}", but in general, it must be remembered that the "--arg name value" option is intended only for passing in strings.

A possibility:

JSON_STRING='{"bucketname":"'"$BUCKET_NAME"'","objectname":"'"$OBJECT_NAME"'","targetlocation":"'"$TARGET_LOCATION"'"}'

Generate a json with variable value from a file using bash, Heredocs perform variable expansion, so you can do something like. SSID=$(cat /sys/class/net/wlan0/address | tail -c 10 | tr -d ":") PW=$(cat  creating json object with variables. Ask Question Asked 7 years, 8 months ago. Active 2 years, Try this to see how you can create a object from strings.

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

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

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"

For homework, read this page carefully: Security implications of forgetting to quote a variable in bash/POSIX shells


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:

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

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

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

A shell command to create JSON: jo, I got tired of attempting to get shell scripts to produce valid JSON. It gets merrier if an element contains an environment variable: open double, and if strings contain quotes, it becomes almost impossible to make a script  The function JSON.stringify will turn your json object into a string: var jsonAsString = JSON.stringify(obj); In case the browser does not implement it (IE6/IE7), use the JSON2.js script. It's safe as it uses the native implementation if it exists.

If you need to build a JSON representation where members mapped to undefined or empty variables should be ommited, then jo can help.

#!/bin/bash

BUCKET_NAME=testbucket
OBJECT_NAME=""

JO_OPTS=()

if [[ ! "${BUCKET_NAME}x" = "x" ]] ; then
        JO_OPTS+=("bucketname=${BUCKET_NAME}")
fi

if [[ ! "${OBJECT_NAME}x" = "x" ]] ; then
        JO_OPTS+=("objectname=${OBJECT_NAME}")
fi

if [[ ! "${TARGET_LOCATION}x" = "x" ]] ; then
        JO_OPTS+=("targetlocation=${TARGET_LOCATION}")
fi

jo "${JO_OPTS[@]}"

Bash jq command – Linux Hint, But JSON data can't be read easily from JSON file by using bash script like other uses a domain specific language for working with JSON data. jq is not a built-in command. Suppose, you have declared a JSON variable named JsonData in the When you will work with JSON data and want to parse or manipulate data  I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the JSON string and them fo

Guide to Linux jq Command for JSON Processing, It's also possible to download the binary directly or build it from the source. In this example, we echo a simple JSON string and pipe it directly  The printf builtin command gives a powerful way of drawing string format. As this is a Bash builtin, there is a option for sending formatted string to a variable instead of printing on stdout: echo ${a[@]} 36 18 one word hello world! hello world! hello world! There are seven strings in this array. So we could build a formatted string containing

Building JSON command with bash script, JSON RPC expects each parameter as separate strings. But the way I built it was by preppending the leading special chars to a variable, then appending each  Using variables in bash file. You can define variable in bash file by the same way which are mentioned in above examples. You have to create file with .sh or .bash extension to run bash script. Example-6: Creating simple bash script. Copy the following code in a text editor and save the file with bash extension. In this script, one string and

command line - parse json with default bash only, for developers to learn, share their knowledge, and build their careers. It expects two arguments. [root@localhost Desktop]# cat data.json | jsonValue id 4568734 GrepLine () { #https://askubuntu.com/questions/952467/extracting-a-​specific-string-after-a-given-string-from-html-file-using-a-bash-sc  Update. Bamboo does not parse variable content in any way, i.e. the content is always just a string. The problem you are encountering is passing a JSON string as a parameter to AWS CloudFormation via the AWS CloudFormation Stack task, which expects those parameters to be passed into the Parameters field as a JSON string in turn, e.g.:

Comments
  • See: Difference between single and double quotes in bash
  • See: Correct shell variable capitalization.
  • Excellent advice: use the right parser/generator for the task at hand. Applies to JSON, CSV, XML, ...
  • is there an extra " after $BUCKET_NAME
  • Clever. I always forget you can mix single and double quote strings.
  • Found this question and its answers, all from 2018. But then weirdly, down here at the bottom is your answer, which you wrote only 4 hours ago. So +1 for this great-looking utility, but also +1 for the weird coincidence.