JSON 空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1543791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:20:04  来源:igfitidea点击:

JSON empty string

jsonstring

提问by

why does the JSON.stringify-Function converts a string.Empty ("") to a "null"-String? The problem, why i'm not using:

为什么 JSON.stringify-Function 将 string.Empty ("") 转换为 "null"-String?问题,为什么我不使用:

JSON.parse(json, function(key, value) {
    if (typeof value === 'string') {
        if (value == 'null')
            return '';
        return value;
    }
});

...is, if somebody really write "null" (is very unlikely, but possible), i have a problem to...

...是,如果有人真的写“null”(不太可能,但可能),我有一个问题......

thank for each answer!

感谢每个答案!

回答by John

Old question - but its the top result when you search for 'json stringify empty string' so I'll share the answer I found.

老问题 - 但它是搜索“json stringify empty string”时的最佳结果,所以我将分享我找到的答案。

This appears to be a bug in certain versions of IE8, where empty DOM elements return a value which looks like an empty string, evaluates true when compared to an empty string, but actually has some different encoding denoting that it is a null value.

这似乎是 IE8 某些版本中的错误,其中空 DOM 元素返回一个看起来像空字符串的值,与空字符串相比评估为 true,但实际上有一些不同的编码表示它是一个空值。

One solution is to do a replace whenever you call stringify.

一种解决方案是在调用 stringify 时进行替换。

JSON.stringify(foo, function(key, value) { return value === "" ? "" : value });

JSON.stringify(foo, function(key, value) { return value === "" ? "" : value });

See also http://blogs.msdn.com/b/jscript/archive/2009/06/23/serializing-the-value-of-empty-dom-elements-using-native-json-in-ie8.aspx

另见http://blogs.msdn.com/b/jscript/archive/2009/06/23/serializing-the-value-of-empty-dom-elements-using-native-json-in-ie8.aspx

回答by John

now the esiest solution for this problem is, to pack the "document.getElementById('id').value" expression in the constructor of the String class:

现在解决这个问题最简单的方法是在 String 类的构造函数中打包“document.getElementById('id').value”表达式:

JSON.stringify({a:new String(document.getElementById('id').value)}); -> {"a":""}

i can't find the primary problem, but with this, it's working well in Internet Explorer as well in FireFox.

我找不到主要问题,但是有了这个,它在 Internet Explorer 和 FireFox 中都运行良好。

i'm not very happy with this dirty solution, but the effort is not to much.

我对这个肮脏的解决方案不太满意,但努力并不多。

JSON library: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

JSON 库:https: //github.com/douglascrockford/JSON-js/blob/master/json2.js