7

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

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...

thank for each answer!

Matthias
  • 7,432
  • 6
  • 55
  • 88
  • Which JSON.stringify function? What programming language? (JavaScript, I guess?) What JSON library are you using? – Jesper Oct 09 '09 at 13:41
  • FireFox says something else: JSON.stringify({a:''}); -> {"a":""} – jantimon Oct 09 '09 at 13:51
  • yes, javascript. I use: http://www.json.org/json2.js @Ghommey: you're right! In FireFox works correctly.... but not in the Internet Explorer.... –  Oct 09 '09 at 13:58
  • This may be you aswer: http://stackoverflow.com/questions/30325400/json-stringify-returns-empty-string – Cristiana Pereira Mar 18 '16 at 11:36

2 Answers2

4

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

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.

One solution is to do a replace 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

John
  • 1,502
  • 2
  • 13
  • 40
1

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

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.

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