作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将值中包含引号的字符串解析为 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。
const str = "<h3>&&&""xx;;</h3> <h2>";
const obj = { 'test1': '<h3>&&&""xx;;</h3> <h2> ', 'test2': 'help'};
console.log(htmlDecode(str)) // <h3>&&&""xx;;</h3> <h2>
console.log(htmlDecode(JSON.stringify(obj))) // {"test1":"<h3>&&&""xx;;</h3> <h2> ","test2":"help"}
//Creating New Object With Escaped String
var newObj={};
Object.keys(obj).forEach(function(key){
var newVal=escapeString(htmlDecode(obj[key]));
newObj[key]=newVal;
});
console.log(newObj);
function htmlDecode(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
//To Escape Characters like Quote
function escapeString(jsonStr){
return jsonStr.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
}
关于javascript - 我想在 JSON.stringify() 之后播放 htmlDecode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57583772/
使用登录后,我想吐出用户名。 但是,当我尝试单击登录按钮时, 它给了我力量。 我看着logcat,但是什么也没显示。 这种编码是在说。 它将根据我在登录屏幕中输入的名称来烘烤用户名。 不会有任何密码。
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
我是一名优秀的程序员,十分优秀!