如何在JavaScript中使用JSON.parse()解析HTML字符串?

Oma*_*ivo 3 javascript asp.net-mvc parsing json

我有一个ASP.NET MVC应用程序返回一个JSON字符串到VIEW.

// Parsing the model returned on the VIEW
var jsonString = '@Html.Raw(Model.ToJson())';
var jsonObj = JSON.parse(jsonString);
Run Code Online (Sandbox Code Playgroud)

问题是我无法解析因为jsonString包含诸如"\"和"'"之类的字符.

//Sample string
{ "description" : "<p>Sample<span style=\"color: #ff6600;\"> Text</span></strong></p>" }
Run Code Online (Sandbox Code Playgroud)

cmb*_*ley 5

JSON是有效的JavaScript,所以你可以这样做:

var jsonObj = @Html.Raw(Model.ToJson());
Run Code Online (Sandbox Code Playgroud)

仅供参考,JSON解析失败的原因是因为虽然它们"被转义\以使其成为有效的JSON,但反斜杠本身需要在字符串中转义以便JSON解析器可以看到它们.相比:

JSON.parse('"quote: \""');  // error: unexpected string
JSON.parse('"quote: \\""'); // 'quote: "'
Run Code Online (Sandbox Code Playgroud)

此示例还应阐明反斜杠发生的情况:

var unescaped = '\"', escaped = '\\"';

console.log(unescaped, unescaped.length); // '"',  1
console.log(escaped, escaped.length);     // '\"', 2
Run Code Online (Sandbox Code Playgroud)