JSON Usage


Convert JSON text to a JavaScript object

One of the most common uses of JSON is to read JSON data from a web server (as a file or as an HttpRequest), convert the JSON data to a JavaScript object, and then use that data in a web page.

To explain it more simply, we use a string as input for demonstration (instead of a file).


JSON Example - Object from String

Create a JavaScript string containing JSON syntax:

var txt = '{ "sites" : [' + '{ "name":"Example Tutorial" , "url":"www.example.com" },' + '{ "name":"google" , "url":"www.google.com" },' + '{ "name":"Weibo" , "url":"www.weibo.com" ]}';

Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() can be used to convert JSON text to a JavaScript object.

The eval() function uses the JavaScript compiler, which can parse JSON text and then generate a JavaScript object. The text must be wrapped in parentheses to avoid syntax errors:

var obj = eval ("(" + txt + ")");

Use the JavaScript object in a web page:

Example

var txt = '{ "sites" : [' + '{ "name":"Example Tutorial" , "url":"www.example.com" },' + '{ "name":"google" , "url":"www.google.com" },' + '{ "name":"Weibo" , "url":"www.weibo.com" ]}'; var obj = eval ("(" + txt + ")"); document.getElementById("name").innerHTML=obj.sites[0].name document.getElementById("url").innerHTML=obj.sites[0].url

Try it yourself »

JSON Parser

lampThe eval() function can compile and execute any JavaScript code. This hides a potential security issue.

Using a JSON parser to convert JSON to a JavaScript object is a safer practice. 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) standard include native support for JSON.

Web Browser Support Web Software Support
  • Firefox (Mozilla) 3.5
  • Internet Explorer 8
  • Chrome
  • Opera 10
  • Safari 4
  • jQuery
  • Yahoo UI
  • Prototype
  • Dojo
  • ECMAScript 1.5

Try it yourself »

For older browsers, you can use a JavaScript library: https://github.com/douglascrockford/JSON-js

The JSON format was originally originally specified by Douglas Crockford

Other extensions