In JavaScript, a JSON representation would be a string that displays what is in an Object.
Consider:
var obj = new Object;
obj = {
name: 'Steve',
favorite_color: 'blue',
age: 34,
programmer: true
};
In JSON format, the same data would look like this:
{"name":"Steve","favorite_color":"blue","age":34,"programmer":true}
JSON is a string, just like XML. An object is a collection of functions and attributes.
For quick reference, here's the correct syntax:
var json = new String; var hash = $H(obj); // Objects json = Object.toJSON(obj); // Hashes json = $H(obj).toJSON(); json = hash.toJSON();
Object.toJSON(obj);
Result:
obj.toJSON();
Result:
Even though the variable is already cast as a Prototype Object, running obj.toJSON() will not work. This will throw a JS error, "obj.toJSON is not a function"
Object(obj).toJSON();
Result:
Recasting as an Object and then calling toJSON() on it immediately afterwards will not work, either.
A Prototype Hash is a JavaScript Object acting solely as an associative array. Use $H to convert an Object to a Hash, or to access Hash functions.
$H(obj).toJSON();
Result:
Create a new hash: var hash = new Hash(obj); OR var hash = $H(obj);
hash.toJSON();
This is one part where Prototype deviates from consistency. The toJSON method will not work on an Object, but it will with a Hash.
Result:
Hash.toJSON(obj);
Again, this is confusing, since Object.toJSON(obj) would work properly. Replacing Object with Hash does not work.
Result:
Hash(obj).toJSON();
Like Object(obj).toJSON(), this doesn't work either. It does throw a different type of error, though, and this one won't show up in the Firebug console unless "Break on All Errors" is enabled. It will display an error in Firefox's Error Console, which is in the Prototype script (v1.6.1 used here).
Result: