【发布时间】:2019-12-26 06:27:25
【问题描述】:
我想将值中包含引号的字符串解析为 JSON。
JSON.stringify() 的字符串是 htmlDecode() 之后,转换为",JSON.parse()时出错。
new DOMParser().parseFromString(input, "text/html");在此过程中 除了“quot;”可以执行吗
或者还有其他方法吗?
<script>
const str = "< ;h3> ;& ;& ;& ;" ;" ;xx;;< ;/h3> ; < ;h2> ;";
const obj = { "test1": "< ;h3> ;& ;& ;& ;" ;" ;xx;;&l t;/h3> ; < ;h2> ; ", "test2": "help" };
function htmlDecode(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
console.log(htmlDecode(str)) // <h3>&&&""xx;;</h3> <h2>
console.log(htmlDecode(JSON.stringify(obj))) // {"test1":"<h3>&&&""xx;;</h3> <h2> ","test2":"help"}
console.log(JSON.parse(htmlDecode(JSON.stringify(obj)))) // VM49:1 Uncaught SyntaxError: Unexpected string in JSON at position 18 at JSON.parse (<anonymous>)
</script>
</body>
如果字符串不包含qout; JSON 解析运行良好。
const quotIsNotObj = { "test1": "< ;h3> ;& ;& ;& ;xx;;< ;/h3> ; < ;h2> ; ", "test2": "help" };
console.log(JSON.parse(htmlDecode(JSON.stringify(successObj)))) // {"test1":"<h3>&&&xx;;</h3> <h2> ","test2":"help"}
【问题讨论】:
-
JSON 与 HTML 无关——你所做的一切毫无意义,你不能将 HTML 解析为 JSON
-
@JaromandaX 我想一次解码 json 中的所有字符串。如果值不是qout;解析得很好。
-
哦,对,所以
textContent不是正确的 JSON - 抱歉,我没有阅读htmlDecode中的完整代码(假设你返回的是 html,我的错) - 是的。 ..这是一个问题好吧 -
1) JSON 中的空格是格式错误吗?他们在这里呈现的方式,他们不会得到那样的输出。 2) 你想以 JS 对象还是 HTML 结束?
标签: javascript html json dom