W3Schools.com

JSON HowTo


Converting a JSON Text to a JavaScript Object

One of the most common use 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 use 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 type="text/javascript">
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>

Try it yourself »

JSON Parser

lamp  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 newer browsers and in the newest ECMAScript (JavaScript) standard.

Web Browsers SupportWeb 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, a JavaScript library is available at https://github.com/douglascrockford/JSON-js

The JSON format was originally specified by Douglas Crockford



WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$3.98 Unlimited Hosting
Premium Website Design
WEB BUILDING
XML Editor - Free Trial!
FREE Website BUILDER
Best Website Templates Top CSS Templates
CREATE HTML Websites
EASY WEBSITE BUILDER
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE