gpt4 book ai didi

javascript - Javascript 的 JSON.parse 有问题吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:50:36 24 4
gpt4 key购买 nike

console.log(JSON.parse('{"data":"{\"json\":\"rocks\"}"}'));

给出错误(在 Firefox 和 Chrome 的控制台上测试)。这是 JSON.parse 的错误吗?使用 PHP 进行测试时,同样可以很好地解码。

print_r(json_decode('{"data":"{\"json\":\"rocks\"}"}', true));

最佳答案

此字符串在 PHP 和 JS 中的处理方式不同,即您会得到不同的结果。

在 PHP 中,单引号字符串中唯一的转义序列是 \\\'。根据documentation,所有其他的都按字面输出。 :

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

另一方面,在 JS 中,如果字符串包含无效的转义序列,the backslash is discarded (CV 表示字符值):

  • The CV of CharacterEscapeSequence :: NonEscapeCharacter is the CV of the NonEscapeCharacter.
  • The CV of NonEscapeCharacter :: SourceCharacter but not EscapeCharacter or LineTerminator is the SourceCharacter character itself.

引用本身可能没有帮助,但如果您点击链接并查看语法,它应该会变得清晰。


所以在 PHP 中字符串将包含 \" 而在 JS 中它只会包含 ",这使得它无效的 JSON:

{"data":"{"json":"rocks"}"}

如果你想在 JS 中创建一个文字反斜杠,你必须转义它:

'{"data":"{\\"json\\":\\"rocks\\"}"}'

关于javascript - Javascript 的 JSON.parse 有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12655517/

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