Falcon80 Logo
Parsing a JSON File

A quick and dirty way to parse JSON data format is to use the eval function.

JSONObject = eval('(' + '{"firstName": "Isabelle", "lastName": "Solomon"}' + ')');

The eval function will parse the JSON data and return the data object to the variable JSONObject. You can now access the values of firstName and lastName as JSONObject.firstName and JSONObject.lastName respectively.

However, using the eval function is not the best way to parse a JSON file for security reasons. A better way is to include the JSON javascript parser json2.js. The parser can be downloaded from here. Once you include the json2.js file in your javascript code, you can use the JSON.parse function like this:

JSONObject = JSON.parse('{"firstName": "Isabelle", "lastName": "Solomon"}');

Both the eval function and JSON.parse can be used with a variable that contains the JSON data object:

jsonData = {"firstName": "Isabelle", "lastName": "Solomon"};
JSONObject = eval('(' + jsonData + ')');
JSONObject = JSON.parse(jsonData);

This is especially relevant when using JSON with AJAX. When a file containing JSON data is fetched using AJAX, the xmlhttp.responseText variable contains the raw data. Either the eval function or the JSON.parse function can be used to parse the data as follows.

JSONObject = eval('(' + xmlhttp.responseText + ')');
JSONObject = JSON.parse(xmlhttp.responseText);

Example using eval function:


<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">

function init()
{
var JSONObject = eval('(' + '{"firstName": "Isabelle", "lastName": "Solomon"}' + ')');
alert(JSONObject.firstName);
}
</script>
<title>JSON - Parsing Javascript using eval</title>
</head>
<body onload="init();">
</body>
</html>




Example using json2.js parser

To try out the example, place the json2.js file in the same folder in your web server/computer where you have the example file.

<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script src="json2.js"></script>
<script type="application/javascript">
function init()
{
var JSONObject = JSON.parse( '{"firstName": "Isabelle", "lastName": "Solomon"}' );
alert(JSONObject.firstName);
}
</script>
<title>JSON - Parsing Javascript using eval</title>
</head>
<body onload="init();">
</body>
</html>