Updates Below
If you already have a JavaScript object, you can utilize the JSON.stringify
function to convert it into a JSON string. Douglas Crockford, the originator of JSON, has provided an implementation of JSON.stringify
in json2.js which can be found on his github page. Although many browsers now have built-in support for this functionality due to standardization, there are still some that require the use of a utility script like Crockford's or another.
Generating JSON from an object graph is relatively straightforward as JSON is designed to be easily produced and consumed.
JSON is essentially a subset of JavaScript Object Literal notation. Therefore, a JavaScript object such as:
{"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}
]
}
is identical to its JSON counterpart. If you were to include this in a file for reading into memory or server retrieval, this is exactly how you would structure it. When embedding a JSON string within JavaScript code, simply enclose it in quotes like so:
var aJSONString = '{"bindings": [' +
'{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},' +
'{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}' +
']' +
'}';
It is important to note that all keys and strings in JSON must be surrounded by double quotes, unlike JavaScript objects that may not require them. For instance:
{foo: 'bar'}
would need to be converted to:
{"foo": "bar"}
in JSON format.
Update: Regarding your comment below: Apologies for any confusion earlier.
Constructing tree structures in JavaScript is quite simple. JavaScript objects are essentially flexible collections of key/value pairs resembling maps or dictionaries. For example:
// Start with an empty object
var obj = {};
// Add a leaf to it
obj.foo = {};
// Add another leaf under the first one with the value 42
obj.foo.subfoo = 42;
// Include a new leaf at the root level; an array containing 1, 2, and 3
obj.bar = [1, 2, 3];
alert(JSON.stringify(obj));
// '{"foo: {"subfoo": 42}, "bar": [1, 2, 3]}'
You can represent this as a literal as shown below:
var obj = {
foo: {
subfoo: 42
},
bar: [1, 2, 3]
};
An interesting aspect is that the values on the right-hand side in a literal can be variables, where their current value will be used just like an assignment. The following snippet achieves the same result as above:
var fortytwo = 42;
var obj = {
foo: {
subfoo: fortytwo
},
bar: [1, 2, 3]
};