HOME HTML CSS JAVASCRIPT SQL PHP JQUERY XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

JSON HowTo


Converting a JSON Text to a JavaScript Object

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

For simplicity, this can be demonstrated by using a string as input (instead of a file).


JSON Example - Object From String

Create a JavaScript string containing JSON syntax:

var txt = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

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

The eval() function uses the JavaScript compiler which will parse the JSON text and produce a JavaScript object. The text must be wrapped in parenthesis to avoid a syntax error:

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

Use the JavaScript object in your page:

Example

<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>

<script>
document.getElementById("fname").innerHTML = obj.employees[1].firstName;
document.getElementById("lname").innerHTML = obj.employees[1].lastName;
</script>

Try it yourself »

JSON Parser

Note The eval() function can compile and execute any JavaScript. This represents a potential security problem.

It is safer to use a JSON parser to convert a JSON text to a JavaScript object. A JSON parser will recognize only JSON text and will not compile scripts.

In browsers that provide native JSON support, JSON parsers are also faster.

Native JSON support is included in all major browsers and in the latest ECMAScript (JavaScript) standard.

Web Browsers SupportWeb Software Support
  • Firefox 3.5
  • Internet Explorer 8
  • Chrome
  • Opera 10
  • Safari 4
  • jQuery
  • Yahoo UI
  • Prototype
  • Dojo
  • ECMAScript 1.5

Try it yourself »

For older browsers, a JavaScript library is available at https://github.com/douglascrockford/JSON-js

The JSON format was originally specified by Douglas Crockford



Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates

SHARE THIS PAGE