JSON Usage
Converting JSON Text to JavaScript Object
One of the most common uses of JSON is to read data from a web server (as a file or an HttpRequest), convert the JSON data into a JavaScript object, and then use the data in a web page.
For simplicity in explanation, we will demonstrate using a string as input (instead of a file).
JSON Example - Object from String
Create a JavaScript string containing JSON syntax:
var txt = '{ "sites" : [' +
'{ "name":"tutorialpro.org" , "url":"www.tutorialpro.org" },' +
'{ "name":"google" , "url":"www.google.com" },' +
'{ "name":"微博" , "url":"www.weibo.com" } ]}';
Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() can be used to convert JSON text into a JavaScript object.
The eval() function uses the JavaScript compiler to parse the JSON text and produce a JavaScript object. The text must be enclosed in parentheses to avoid syntax errors:
Using the JavaScript object in a web page:
Example
var txt = '{ "sites" : [' +
'{ "name":"tutorialpro.org" , "url":"www.tutorialpro.org" },' +
'{ "name":"google" , "url":"www.google.com" },' +
'{ "name":"微博" , "url":"www.weibo.com" } ]}';
var obj = eval ("(" + txt + ")");
document.getElementById("name").innerHTML = obj.sites[0].name;
document.getElementById("url").innerHTML = obj.sites[0].url;
JSON Parser
Using a JSON parser to convert JSON into a JavaScript object is safer. A JSON parser only recognizes JSON text and does not compile scripts.
In browsers, this provides native JSON support, and JSON parsers are faster.
Newer browsers and the latest ECMAScript (JavaScript) standards include native support for JSON.
Web Browser Support | Web Software Support |
---|---|
Firefox (Mozilla) 3.5<br>Internet Explorer 8<br>Chrome<br>Opera 10<br>Safari 4 | jQuery<br>Yahoo UI<br>Prototype<br>Dojo<br>ECMAScript 1.5 |
For older browsers, you can use a JavaScript library: https://github.com/douglascrockford/JSON-js
The JSON format was originally specified by Douglas Crockford.