JSON

The JSON format is a way to markup schema to display data. XML would be a comparable format.

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.

Converting to JSON

Converting an Object to a JSON string using Prototype has a few quirks. Only certain syntaxes will work properly.

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();

Prototype Object

Correct Syntax

Object.toJSON(obj);

Result:

Incorrect Syntax #1

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"

Incorrect Syntax #2

Object(obj).toJSON();

Result:

Recasting as an Object and then calling toJSON() on it immediately afterwards will not work, either.

Converting a Hash to JSON

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.

Correct Syntax #1

$H(obj).toJSON();

Result:

Correct Syntax #2

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:

Inorrect Syntax #1

Hash.toJSON(obj);

Again, this is confusing, since Object.toJSON(obj) would work properly. Replacing Object with Hash does not work.

Result:

Inorrect Syntax #2

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: