Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo json over command line into file

Tags:

json

linux

echo

cmd

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.

like image 962
David Avatar asked Oct 09 '14 10:10

David


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 open a JSON file in Terminal?

Vim is a file opener software that can be used to open the JSON file on Linux platform. GitHub Atom is a cross-platform tool to open JSON files. Other than these tools, you can use web browsers like Google Chrome and Mozilla Firefox to open JSON files, which we discuss in detail later.


1 Answers

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

like image 156
Arkenklo Avatar answered Sep 30 '22 15:09

Arkenklo