简体   繁体   中英

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

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

如果要创建有效的Javascript字符串,则需要转义反斜杠和撇号:

var jsonString = '@Html.Raw(Model.ToJson().Replace("\\", "\\\\").Replace("'", "\\'"))';

There you go:

using Newtonsoft.Json;

JsonConvert.SerializeObject(your html string here);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM