JavaScript is a general purpose programming language that was introduced as the page scripting language for Netscape Navigator. It is widely believed to be a subset of Java, but it is not. It is a Scheme-like language with C-like syntax and soft objects. JavaScript was standardized in the ECMAScript Language Specification, Third Edition.
JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.
var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
In this example, an object is created containing a single member "bindings", which contains an array containing three objects, each containing "ircEvent", "method", and "regex" members.
Members can be retrieved using dot or subscript operators.
myJSONObject.bindings[0].method // "newURI"
To convert a JSON text into an object, use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure.
var myObject = eval('(' + myJSONtext + ')');
The eval
function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval
is indicated when the source is trusted. This is commonly the case in web applications when a web server is providing both the base page and the JSON data. There are cases where the source is not trusted. In particular, clients should never be trusted.
When security is a concern it is better to use a JSON parser. A JSON parser will only recognize JSON text and so is much safer:
var myObject = myJSONtext.parseJSON();
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.
var myJSONText = myObject.toJSONString();
The open source code of a JSON parser and JSON stringifier is available. When minified it is only about 1.5K.