Convert JSON in JavaScript

In this lesson you can learn how to convert JSON text to a JavaScript object, and to convert JavaScript objects into a JSON string that can be transfered to different aplications.

Convert JSON text to JavaScript object

One of the most common use of JSON is to fetch JSON data from a web server, as a string that can be converted to JavaScript object to be used in web page.
Because JSON syntax is a subset of JavaScript syntax, the eval() function can be used to convert a JSON text into a JavaScript object, using this syntax:
var obj = eval ('(' + json_string + ')');

- In the following example, the "jsnstr" variable contains a string with a JSON object (The string can be fetched with Ajax, for example from a PHP script, or from a file on server).
Web site: <span id="wurl"></span><br/>
Title: <span id="wtitle"></span>

<script type="text/javascript">
// example of what is received from server
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses", "users": 1500}';

// parse the "jsnstr", and store the JSON object in "obj"
var obj = JSON.parse(jsnstr);

// uses the JavaScript object, adds the values from "url", and "title" in web page
document.getElementById('wurl').innerHTML = obj.url;
document.getElementById('wtitle').innerHTML = obj.title;
</script>

- The values of "url", and "title" properties are added in HTML tags in web page.
The example above will produce the following results:
Web site: http://coursesweb.net/
Title: Web Development Courses

- The eval() function parses the JSON string and produce a JavaScript object. Because the eval() function can compile and execute any JavaScript code added in the string, this represents a potential security problem.
It is safer to use a JSON parser, which recognizes only JSON text, rejecting all scripts. You can download the JavaScript JSON parser at https://github.com/douglascrockford/JSON-js.
Including the json2.js file on a web page allows you to take advantage of the JSON object, which has the following useful methods:
        • JSON.parse(json_string) - converts a JSON string into a JavaScript object.
        • JSON.stringify(javascript_object) - converts a JavaScript object into a JSON string.

- The modern browsers support native JSON, and is part of the newest ECMAScript (JavaScript) standard, so, JSON parser can be used without including the "json2.js" file, and it is much faster.

Here's the same example, but using JSON.parse() method.
Web site: <span id="wurl"></span><br/>
Title: <span id="wtitle"></span>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
// example of what is received from server
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses", "users": 1500}';

// parse the "jsnstr", and store the JSON object in "obj"
var obj = JSON.parse(jsnstr);

// uses the JavaScript object, adds the values from "url", and "title" in web page
document.getElementById('wurl').innerHTML = obj.url;
document.getElementById('wtitle').innerHTML = obj.title;
</script>

JSON.parse() can be used to parse JSON strings that contains only values which are objects or arrays (with numeric and string type data), if the object contains complex data (methods, functions), the JSON.parse() will return "unexpected keyword" error. In this case, if you are sure that date are safe, use eval().


Convert JavaScript object to JSON string

To convert JavaScript object to JSON string you can use the JSON.stringify() method.
This is necessary especially in Ajax applications, when you want to transfer data from JavaScript to a script on server.
- In the next example it is created a JavaScript object containing an array, and an object. We use the JSON.stringify() method to convert the object into a JSON string, then, to show the results, the string is displayed in a <div> in webpage.
JSON string:
<div id="showjson"></div>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
// object with an arrays and an object
var obj = {
 "courses": ['html', 'php', 'ajax'],
 "site": {"url": 'http://coursesweb.net/', "title": 'Web Development Courses', "users": 1500}
}

// converts the "obj" into a JSON string
var jsonstr = JSON.stringify(obj);

// displays the JSON text in the HTML element with id="showjson"
document.getElementById('showjson').innerHTML = jsonstr;
</script>
This example will create the following result:
JSON string:
{"courses":["html","php","ajax"],"site":{"url":"http://coursesweb.net/","title":"Web Development Courses","users":1500}}

- Then, this string can be easily converted again into an object (or associative array) in the script on server. For example, in PHP by using json_decode() function.