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));
source share