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!

4
  • Which JSON.stringify function? What programming language? (JavaScript, I guess?) What JSON library are you using? Commented Oct 9, 2009 at 13:41
  • FireFox says something else: JSON.stringify({a:''}); -> {"a":""} Commented Oct 9, 2009 at 13:51
  • yes, javascript. I use: json.org/json2.js @Ghommey: you're right! In FireFox works correctly.... but not in the Internet Explorer.... Commented Oct 9, 2009 at 13:58
  • This may be you aswer: stackoverflow.com/questions/30325400/… Commented Mar 18, 2016 at 11:36

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.