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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23176241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:29:07  来源:igfitidea点击:

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

javascriptjsonasp.net-mvcparsing

提问by Omar Olivo

I have an ASP.NET MVC application returning a JSON string to the VIEW.

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

// 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 jsonStringcontains characters such as "\" and "'".

问题是我无法解析,因为jsonString包含诸如“\”和“'”之类的字符。

//Sample string
{ "description" : "<p>Sample<span style=\"color: #ff6600;\"> Text</span></strong></p>" }

回答by cmbuckley

JSON is valid JavaScript, so you can just do this:

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

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 解析失败的原因是,虽然 JSON"被转义\以使其成为有效的 JSON,但反斜杠本身需要在字符串中转义,以便 JSON 解析器看到它们。比较:

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

回答by Guffa

If you want to create a valid Javascript string, you need to escape backslashes and apostrophes:

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

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

回答by Stoyan Bukovich

There you go:

你去吧:

using Newtonsoft.Json;

JsonConvert.SerializeObject(your html string here);