Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Parse escape newline characters

I have a page where I am trying to parse following json string using JSON.parse

'[{"Name":"Eggs","Complete":false,"Notes":"Notes here\n"},{"Name":"Sugar","Complete":false,"Notes":null}]'

But following code gives error "Uncaught SyntaxError: Unexpected token"

var groceriesJson = JSON.parse(jsonString);

Then I came to know that its because of \n in json string. So I did try this solution. But no luck. Still same error "Uncaught SyntaxError: Unexpected token"

function escapeSpecialChars(jsonString) {

        return jsonString.replace(/\\n/g, "\\n")
              .replace(/\\'/g, "\\'")
              .replace(/\\"/g, '\\"')
              .replace(/\\&/g, "\\&")
              .replace(/\\r/g, "\\r")
              .replace(/\\t/g, "\\t")
              .replace(/\\b/g, "\\b")
              .replace(/\\f/g, "\\f");

      }

 var groceriesJson = JSON.parse(escapeSpecialChars(jsonString));

Any ideas? Thanks

---UPDATE----

I am not creating this string manually, I have c# codes that creates json string from c# objects

 var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
 var groceries = jss.Serialize(Model);

then in javascript codes I have

var jsonString = '@Html.Raw(groceries)'
 var groceriesJson = JSON.parse(escapeSpecialChars(jsonString));
like image 836
sanjeev Avatar asked Oct 17 '14 08:10

sanjeev


People also ask

How do you escape a new line in JSON?

JSON strings do not allow real newlines in its data; it can only have escaped newlines. Snowflake allows escaping the newline character by the use of an additional backslash character.

Is \n allowed in JSON?

In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.

What characters should be escaped JSON?

In JSON the only characters you must escape are \, ", and control codes.


1 Answers

You should just escape the \ as in \\n, your JSON becoming :

'[{"Name":"Eggs","Complete":false,"Notes":"Notes here\\n"},{"Name":"Sugar","Complete":false,"Notes":null}]';

If you cannot have access to the JSON, then your function should be :

function escapeSpecialChars(jsonString) {

    return jsonString.replace(/\n/g, "\\n")
        .replace(/\r/g, "\\r")
        .replace(/\t/g, "\\t")
        .replace(/\f/g, "\\f");

}

 var groceriesJson = JSON.parse(escapeSpecialChars(jsonString));
like image 105
laruiss Avatar answered Oct 10 '22 22:10

laruiss