JSON empty string

why does the JSON.stringify function convert string.Empty (") to" null "-String? Problem, why am I not using:

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

... is, if someone really writes "null" (very unlikely, but possible), I have a problem ...

Thanks for every answer!

+6
json string
source share
2 answers

An old question - but its top result when searching for "json stringify is an empty string", so I will share the answer I’ve found.

This seems to be a bug in some versions of IE8, where empty DOM elements return a value that looks like an empty string, evaluates to true compared to the empty string, but actually has some other encoding, indicating that it is a null value.

One solution is to perform a replacement whenever you call stringify.

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

+4
source share

Now the most difficult solution for this task is to package the expression document.getElementById ('id'). value in the constructor of the String class:

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

I can not find the main problem, but with this it works well in Internet Explorer, as well as in FireFox.

I am not very happy with this dirty decision, but not much effort.

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

+1
source share

All Articles