22

I have a build tool which is creating a versions.json file injected with a json format string.

Initially I was thinking of just injecting the json via an echo, something like below.

json = {"commit_id": "b8f2b8b", "environment": "test", "tags_at_commit": "sometags", "project": "someproject", "current_date": "09/10/2014", "version": "someversion"}

echo -e json > versions.jso

However the echo seems to escape out all of the quote marks so my file will end up something like this:

{commit_id: b8f2b8b, environment: test, tags_at_commit: somereleasetags, project: someproject, current_date: 09/10/2014, version: someproject}

This unfortunately is not valid JSON.

Vivek Pradhan
  • 4,777
  • 3
  • 26
  • 46
David
  • 34,836
  • 11
  • 47
  • 77

2 Answers2

48

To preserve double quotes you need to surround your variable in single quotes, like so:

json='{"commit_id": "b8f2b8b", "environment": "test", "tags_at_commit": "sometags", "project": "someproject", "current_date": "09/10/2014", "version": "someversion"}'
echo "$json" > versions.json

Take into account that this method will not display variables correctly, but instead print the literal $variable.

If you need to print variables, use the cat << EOF construct, which utilizes the Here Document redirection built into Bash. See man bash and search for "here document" for more information.

Example:

commit="b8f2b8b"
environment="test"
...etc

cat << EOF > /versions.json
{"commit_id": "$commit", "environment": "$environment", "tags_at_commit": "$tags", "project": "$project", "current_date": "$date", "version": "$version"}
EOF

If you're looking for a more advanced json processing tool that works very well with bash, I'd recommend jq

tripleee
  • 175,061
  • 34
  • 275
  • 318
Arkenklo
  • 604
  • 6
  • 5
  • what if the json contains an array. like for ex: { "a" : "test", "b": ["test1","test2"] } how can i achieve that? – Tjs Apr 19 '19 at 00:14
  • https://stackoverflow.com/questions/12524437/output-json-from-bash-script/12524510 migt help also – Adiii Mar 29 '20 at 05:26
0

If you want variables in between you can quote does this '"'$variable'"'. Below is the date example.

echo {'"date"' : '"'$(date +"%d_%m_%Y")'"'} > cron_checkpoint.json