gpt4 book ai didi

javascript - JSON 字符串是否支持双引号?

转载 作者:行者123 更新时间:2023-11-28 14:45:46 49 4
gpt4 key购买 nike

当我在 JSON 字符串中通过 \" 转义双引号时,解析器失败。但是,当我使用 JSON.stringify 时,它能够以某种方式正确转义字符串.

我怀疑我没有正确转义双引号。查看代码以获取更多详细信息。

var data = {
"singleQuoteHtml": "<span class='qwer'>content</span>",
"doubleQuoteHtml": "<span class=\"qwer\">content</span>",
"singleQuote": "'hi'",
"doubleQuote": "\"hi\""
};

var dataString = '{"singleQuoteHtml": "<span class=\'qwer\'>content</span>",'
+ '"doubleQuoteHtml": "<span class=\"qwer\">content</span>",'
+ '"singleQuote": "\'hi\'",'
+ '"doubleQuote": "\"hi\"'
+ '}';



function Parse()
{
//Stringify is capable of creating single quotes and double quotes
console.log(JSON.parse(JSON.stringify(data)));

//When I escape double quotes myself the parser fails
//Uncomment to see failure
//console.log(JSON.parse(dataString));
}
<button onclick="Parse();">Parse JSON </button>

最佳答案

字符串文字 '... "\"hi\""...' 计算结果为 ""hi"",不带反斜杠。

反斜杠作为转义序列被字符串文字吞没。

您需要将反斜杠转义为 \\ 才能将实际的反斜杠放入字符串中。

关于javascript - JSON 字符串是否支持双引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46411846/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com