I have an ASP.NET MVC application returning a JSON string to the VIEW.
// Parsing the model returned on the VIEW
var jsonString = '@Html.Raw(Model.ToJson())';
var jsonObj = JSON.parse(jsonString);
The problem is that I am not able to parse because the jsonString contains characters such as "\" and "'".
//Sample string
{ "description" : "<p>Sample<span style=\"color: #ff6600;\"> Text</span></strong></p>" }
JSON is valid JavaScript, so you can just do this:
var jsonObj = @Html.Raw(Model.ToJson());
FYI, the reason the JSON parsing is failing is because the although the " are escaped with \ to make it valid JSON, the backslashes themselves need escaping in the string for them to be seen by the JSON parser. Compare:
JSON.parse('"quote: \""'); // error: unexpected string
JSON.parse('"quote: \\""'); // 'quote: "'
This example should also clarify what's happening to the backslashes:
var unescaped = '\"', escaped = '\\"';
console.log(unescaped, unescaped.length); // '"', 1
console.log(escaped, escaped.length); // '\"', 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With