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

12,096

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
Share:
12,096
Omar Olivo
Author by

Omar Olivo

Updated on June 04, 2022

Comments

  • Omar Olivo
    Omar Olivo almost 2 years

    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>" }