Json.Parse escape newline characters

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

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

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

 var groceriesJson = JSON.parse(jsonString); 

Then I found out that this is because of \n in the json string. So I tried this solution . But no luck. Another "Uncaught SyntaxError: Unexpected token" error

 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 don't create this line manually, I have C # codes that create a json string from C # objects

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

then in javascript codes i

 var jsonString = '@Html.Raw(groceries)' var groceriesJson = JSON.parse(escapeSpecialChars(jsonString)); 
+5
source share
2 answers

You should just exit \ , as in \\n , your JSON will become:

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

If you do not have access to 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)); 
+3
source

Since @Quentin suggests you skip saving the value inside the literal and just do something like this:

 var jsonObject = @Html.Raw(groceries); 
0
source

Source: https://habr.com/ru/post/1204905/


All Articles