Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse HTML string using JSON.parse() in JavaScript?

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>" }
like image 710
Omar Olivo Avatar asked May 09 '26 06:05

Omar Olivo


1 Answers

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
like image 92
cmbuckley Avatar answered May 10 '26 20:05

cmbuckley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!