javascript - JSON.stringify 和 "\u2028\u2029"检查?

标签 javascript json

有时候我see在查看源代码页面(html 查看源代码)中,此代码:

if (JSON.stringify(["\u2028\u2029"]) === '["\u2028\u2029"]') JSON.stringify = function (a) {
    var b = /\u2028/g,
        c = /\u2029/g;
    return function (d, e, f) {
        var g = a.call(this, d, e, f);
        if (g) {
            if (-1 < g.indexOf('\u2028')) g = g.replace(b, '\\u2028');
            if (-1 < g.indexOf('\u2029')) g = g.replace(c, '\\u2029');
        }
        return g;
    };
}(JSON.stringify);
  • JSON.stringify(["\u2028\u2029"]) 有什么问题需要检查?

附加信息:

  • JSON.stringify(["\u2028\u2029"]) 值为 "[""]"
  • '["\u2028\u2029"]' 值也是"[""]"

最佳答案

我认为这可能是一项安全功能。 2028 的 FileFormat.info和 2029有横幅说明

Do not use this character in domain names. Browsers are blacklisting it because of the potential for phishing.

但事实证明,行和段落分隔符 \u2028\u2029 在 ES5 JavaScript 中分别被视为新行。

来自 http://www.thespanner.co.uk/2011/07/25/the-json-specification-is-now-wrong/

\u2028 and \u2029 characters that can break entire JSON feeds since the string will contain a new line and the JavaScript parser will bail out

所以您看到了 JSON.stringify 的补丁。另见 Node.js JavaScript-stringify

编辑:是的,现代浏览器的内置 JSON 对象应该正确处理这个问题。不过,我找不到任何指向实际来源的链接来支持这一点。 Chromium code search没有提到任何需要手动添加此解决方法的错误。看起来像 Firefox 3.5是第一个支持原生 JSON 的版本,not entirely虽然没有错误。 IE8也支持它。因此,假设浏览器已正确实现规范,那么它现在可能是一个不必要的补丁。

关于javascript - JSON.stringify 和 "\u2028\u2029"检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16686687/

相关文章:

javascript - 如何使用ajax从服务器接收回数据?

javascript - 设置为 buttonset() 后禁用单选按钮

javascript - jQuery.proxy() 函数未在 Chrome 中调用

java - JsonObject ("body") 不是字符串

c# - 冲突的 Newtonsoft.Json nuget 版本。

arrays - 如何在 Swift 3 Vapor 中将 JSON 转换为字典

php - 根据屏幕分辨率获取图像

javascript - AngularJS - 无效的正则表达式

python - 如何在 python 中将 JSON 结果转换为 Parquet?

json - 如何从 PostgreSQL 中的 Json 数组中获取元素