Convert JSON text to JavaScript objects

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

To make it easier for you, we use strings as input for presentation (not files).

JSON instance-object from string

Create a JavaScript string with JSON syntax:

var content = '{ "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 JSON text to JavaScript objects.


eval () function uses a JavaScript compiler to parse JSON text and generate JavaScript objects. The text must be enclosed in parentheses to avoid syntax errors:

var obj = JSON.parse(text);

Use the new JavaScript object in your page:


<p id="demo"></p>

document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;

Using eval()

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

It is safer to use a JSON parser to convert JSON to JavaScript objects. The JSON parser only recognizes JSON text, it does not compile scripts.

In the browser, this provides native JSON support, and the JSON parser is faster.

Newer browsers and the latest ECMAScript (JavaScript) standard include native JSON support.

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