Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to stringify JSON in Bash

Tags:

json

bash

jq

I know that jq can take serialized JSON strings to format/filter/modify the content. However, as far as I know the output is always human readable form of JSON. Is there a way in Bash or jq itself, to stringify the output?

For example, given

echo '{"foo" : "bar"}' | jq -r .

I'm looking for an output that is "{\"foo\" : \"bar\"}"

like image 404
Paul Grinberg Avatar asked Oct 26 '25 18:10

Paul Grinberg


2 Answers

By "stringify", you seem to mean "encode a JSON value as a JSON string".

$ echo '{"foo": "bar"}' | jq '@json'
"{\"foo\":\"bar\"}"
like image 111
chepner Avatar answered Oct 28 '25 06:10

chepner


You want -R, aka --raw-input, to make jq treat your input as a string instead of as an object.

echo '{"foo" : "bar"}' | jq -R .
like image 21
Charles Duffy Avatar answered Oct 28 '25 06:10

Charles Duffy