2

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>
5
  • I think that it is related to this other question, check here Commented Jun 29, 2016 at 20:50
  • Tried that as well...but it still shows the backslashes Commented Jun 29, 2016 at 20:51
  • Put white-space: pre; on the HTML you add the string to. Or use a <pre> tag. Commented Jun 29, 2016 at 20:53
  • your text file containing your json has new line characters, the json object doesn't. but that is not a problem, just don't try to display it as a string, create a loop that print ` '"' + key + '" : "' + value + '",\\n' ` for each one of them... Commented Jun 29, 2016 at 20:53
  • 1
    Are you sure the backslashes are not escaping the inner quotes? Commented Jun 29, 2016 at 20:54

1 Answer 1

4

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 }

Sign up to request clarification or add additional context in comments.

6 Comments

There it is. Perfect, thank you! The backslashes are gone. Now I just need to indent the json, instead of having it like one long string.
@Cybernetic JSON.stringify can do the indenting for you. I have that in my snippet.
yeah I'm not sure why mine doesn't indent.
While, nicely formatted, the result is incorrect now. The escape character is required to handle the inner quoting.
@JonSG Agreed, but not necessarily incorrect. Pretty printing is for human readability, so perhaps the OP thought it was more readable without backslashes. Hopefully nothing will try to parse it though.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.