Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build a JSON string with Bash variables

Tags:

json

bash

quoting

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  
like image 932
nad87563 Avatar asked Jan 26 '18 21:01

nad87563


People also ask

How do I pass a JSON variable in Bash?

First, your name property is a string, so you need to add double quotes to it in your json. Second, using single quotes, bash won't do variable expansion: it won't replace $r_name with the variable content (see Expansion of variable inside single quotes in a command in bash shell script for more information).

How do I create a JSON string?

married = false; //convert object to json string var string = JSON. stringify(obj); //convert string to Json Object console. log(JSON. parse(string)); // this is your requirement.

How do you declare a string variable in Bash?

To initialize a string, you directly start with the name of the variable followed by the assignment operator(=) and the actual value of the string enclosed in single or double quotes. Output: This simple example initializes a string and prints the value using the “$” operator.

Can you create variables in JSON?

json has been loaded into a JSONObject named jsonData. Using data. json as your guide, create String variables named name, publisher, and language and set them to the appropriate values from data.


1 Answers

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}' ) 
like image 94
chepner Avatar answered Sep 21 '22 08:09

chepner