Cybernetic Cybernetic - 3 months ago 15x
JSON Question

Interpret backslash characters in json string for pretty display

I have a json string like this:

{ "choice": "gogo", "parameter": "high", "result": "[ { \"value_1\": 1.2, \"feature_1\": \"chicken\", \"prominent\": \"yes\" }, ...

The result portion of the json string has backslash characters, from the newlines in the json. I am trying to escape those characters so that I can show the json in html in a pretty fashion. Is there a way for javascript to interpret those newlines in the string so that it is displayed like this:

"choice": "gogo",
"parameter": "high",
"result": "[ { "value_1": 1.2, "feature_1": "chicken", "prominent": "yes" } ... and so on

I have tried:

Json result to html (Newline)

JSON.stringify output to div in pretty print way

How can I beautify JSON programmatically?

but all of them still output the json with the newline characters showing.

Also tried:

var str = JSON.stringify(obj, null, 2);

but it still shows the backslashes.

Also tried using the pre tag inside the div that houses the json string:

<div id="show_json"><pre></pre></div>


You can replace all of the backslashes:

var obj = {
  "choice": "gogo",
  "parameter": "high",
  "result": "[ { \"value_1\": 1.2, \"feature_1\": \"chicken\", \"prominent\": \"yes\" } ]"
document.body.innerHTML = JSON.stringify(obj, null, 4).replace(/\\/g, "");
body { white-space: pre }