Reading a JSON file in JavaScript using JQuery
2012-06-12
Introduction
JavaScript Object Notation (JSON) is becoming one of the most popular 'lightweight' formats for textual data exchange. JSON is based on standard JavaScript syntax, which makes it easy to read and debug for programmers already familiar with C, C++, Java or JavaScript. It’s simplicity has resulted in widespread adoption in many applications.
This article will explain how to use the JQuery framework in JavaScript to read a JSON formatted file using AJAX.
JQuery
Writing JavaScript that manipulates the Document Object Model (DOM) directly can be very difficult, as not all web browsers have identical DOM implementations. JavaScript libraries attempt to provide a solution to this, by providing a level of abstraction between the DOM and your code. The library then takes care of the inconsistencies between browsers.
JQuery is one of the most popular JavaScript libraries. You can use
the JQuery library in your code by adding the following to the
<head>
section of your page:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" ></script>
Google maintains an API guide that lists all the APIs that are available on their servers for you to use.
AJAX Request
If you have ever tried to request a file using AJAX without using a
JavaScript library, you will be familiar with the
XMLHttpRequest()
function and you may have used code that
looks like the following:
var xmlhttp=false; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @end @*/ // and so on...
JQuery simplifies the task of creating an AJAX request considerably.
Now all that is needed is a single $.ajax()
function
call:
($.ajax({ url: requestURL, success: function (data) { // Process data here } }));
So, the contents of a file could be inserted into a page with the following code:
var dest = $('#destination'); ($.ajax({ url: 'file.txt', success: function (data) { dest.html(data); } }));
Reading JSON with JQuery
Once you know how use JQuery to fetch a file using AJAX, reading a
JSON file is quite simple. All that you need to do is set the
dataType
parameter in the AJAX request. For example:
($.ajax({ url: 'file.json', dataType: "json", success: function (data) { alert(data); } }));
Provided the JSON file was able to be parsed correctly, the
data
variable that is passed into the success
function will contain a proper JavaScript object that matches the
structure of the JSON file.