views:

3773

answers:

5

Hello, I'm trying to figure out what's gone wrong with my json serializing, have the current version of my app with and old one and am finding some surprising differences in the way JSON.stringify() works (Using the JSON library from json.org).

In the old version of my app:

 JSON.stringify({"a":[1,2]})

gives me this;

"{"a":[1,2]}"

in the new version,

 JSON.stringify({"a":[1,2]})

gives me this;

"{"a":"[1, 2]"}"

any idea what could have changed to make the same library put quotes around the array brackets in the new version?

+1  A: 

Here's how I'm dealing with it.

var methodCallString =  Object.toJSON? Object.toJSON(options.jsonMethodCall) :  JSON.stringify(options.jsonMethodCall);
morgancodes
+1  A: 

I'm not that fluent with Prototype, but I saw this in its docs:

Object.toJSON({"a":[1,2]})

I'm not sure if this would have the same problem the current encoding has, though.

There's also a longer tutorial about using JSON with Prototype.

R. Bemrose
+3  A: 

I think a better solution would be to include this just after prototype has been loaded

JSON = JSON || {};

JSON.stringify = function(value) { return value.toJSON(); };

JSON.parse = JSON.parse || function(jsonsring) { return jsonsring.evalJSON(true); };

This makes the prototype function avalible as the standard JSON.stringify() and JSON.parse(), but keeps the native JSON.parse() if it is avalible, so this makes things more compatible with older browsers.

+3  A: 
Bob
+3  A: 

Since JSON.stringify has been shipping with some browsers lately, I would suggest using it instead of Prototype’s toJSON. You would then check for window.JSON && window.JSON.stringify and only include the json.org library otherwise (via document.createElement('script')…). To resolve the incompatibilities, use:

if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}
Raphael Schweikert
No need to check for window.JSON in your own code - the json.org script does this itself
zcrar70
That may be so, but then the whole script file has to be loaded even if it won’t be needed.
Raphael Schweikert