How to get a formatted json string from a json object?

Viewed 3760

I'm storing the output of cat ~/path/to/file/blah | jq tojson in a variable to be used later in a curl POST with JSON content. It works well, but it removes all line breaks. I understand line breaks are not supported in JSON, but I'd like them to be replaced with \n characters so when the data is used it isn't all one line.

Is there a way to do this?

Example:

{
  "test": {
     "name": "test",
     "description": "blah"
  },
  "test2": {
     "name": "test2",
     "description": "blah2" 
  }
}

becomes

"{\"test\":{\"name\":\"test\",\"description\":\"blah\"},\"test2\":{\"name\":\"test2\",\"description\":\"blah2\"}}"

but I'd like it to look like

{\n  \"test\": {\n    \"name\": \"test\",\n    \"description\": \"blah\"\n  },\n  \"test2\": {\n    \"name\": \"test2\",\n    \"description\": \"blah2\" \n  }\n}

I'm actually only converting it to a JSON string so it is able to be posted as part of another JSON. When is it posted, I'd like it to have the format it had originally which can be achieved if there are \n characters.

I can do this manually by doing

cat file | sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g' | sed 's/\"/\\"/g')

but this is not ideal.

2 Answers
Related