In this article we’ll investigate the importance of JSON and why we should use it in our applications. We’ll see that jQuery has got us covered with a very nice convenience function.

Bạn đang xem: Jquery ajax json file example

What is JSON?

JSON stands for JavaScript Object Notation. In simple terms JSON is a way of formatting data for, e.g., transmitting it over a network. In this article we will look at loading JSON data using an HTTP GET request (we can also use other verbs, such as POST).

Why would we choose JSON over say XML? The key advantage of using JSON is efficiency. JSON is less verbose & cluttered, resulting in fewer bytes and a faster parse process. This allows us to process more messages sent as JSON than as XML. Moreover, JSON has a very efficient and natural object representation leading khổng lồ formats such as BSON, where JSON-like objects are stored in a binary format.

Now let’s see how jQuery can help us load JSON-encoded data from a remote source. For the impatient among you, there’s a kiểm tra towards the kết thúc of the article.

JSON jQuery Syntax

The $.getJSON() method is a handy helper for working with JSON directly if you don’t require much extra configuration. Essentially, it boils down khổng lồ the more general $.ajax() helper, with the right options being used implicitly. The method signature is:

$.getJSON(url, data, success);

Besides the required URL parameter we can pass in two optional parameters. One represents the data to lớn sover to lớn the hệ thống, the other one a callbaông chồng lớn trigger in case of a successful response.

So the three parameters correspond to:

The url parameter is a string containing the URL lớn which the request is sent. The optional data parameter is either an object or a string that is sent khổng lồ the hệ thống with the request. The optional success(data, textStatus, jqXHR) parameter is a callback function executed only if the request succeeds.

In the simplest scenario we only care about the returned object. In this case, a potential success callbaông xã would look lượt thích this:

function success(data)

As mentioned, the same request can be triggered with the more verbose $.ajax() điện thoại tư vấn. Here we would use:


Let’s see this in practice using a little kiểm tra.

A Sample Application

We will start a local VPS that serves a static JSON tệp tin. The object represented by this tệp tin will be fetched and processed by our JavaScript code. For the purposes of our demo we’ll use Node.js to lớn provide the server (although any server will do). This means we’ll need the following three things:

A working installation of Node.js. The node package manager (npm). A global installation of the http-server package.

The first two points are platform-dependent. If you need some help getting either of them set up, you might want to check out our tutorial: A Beginner’s Guide khổng lồ npm — the Node Package Manager, or Node’s tải về page (npm comes bundled with Node).

The third point can be achieved by running the following from your terminal:

npm install http-server -g

If you find yourself needing a suvì prefix (-nix systems) or an elevated comm& prompt to lớn perkhung this global installation, you should consider changing the location of global packages.

Once these requirements are met we can put the following three files in a new folder:

example.js is the JavaScript tệp tin khổng lồ request the data. example.json is the example JSON file to lớn represent our object. index.html is the HTML page khổng lồ Gọi the JavaScript và display the data.

From the commvà prompt we can simply invoke http-hệ thống within the new folder. Now http://localhost:8080 should be running the test.

The Sample JavaScript

The following code is the complete client-side lô ghích. It waits for the DOMContentLoaded loaded event before attaching an sự kiện handler to the clichồng sự kiện of the element with the ID get-data. When this element is clicked we attempt lớn load the JSON from the VPS using $.getJSON(), before processing the response and displaying it on the screen.

$(document).ready(function () ); showData.empty(); if (items.length) }); showData.text("Loading the JSON file."); }); });

Besides converting parts of the object lớn an unordered list, the full object is also printed in the browser’s debugging console. The output is generated in the

element with the ID show-data. Even though the element is being reset for every request, we only fill it if the resulting JSON object contains any items at all. Of course, for our example the data is fixed, however, in general any kind of response is possible.

Note that we also set some text for the output

. If we insert some (artificial) delay for the JSON retrieval, we will see that this actually executes before any result of the $.getJSON request is displayed. The reason is simple: By mặc định $.getJSON is non-blocking, i.e., async. Therefore, the callback will be executed at some (unknown) later point in time.

Xem thêm: Baạch Tuộc Đông Lạnh (Size Vừa)Homefarm, Bạch Tuộc Tươi Sạch, Đảm Bảo Chất Lượng

Distilling the source to lớn obtain the crucial information yields the following block:

$("#get-data").click(function () ); });

Here we only wire the link to lớn trigger the start of the $.getJSON helper before printing the returned object in the debugging console.

The Sample JSON

The sample JSON file is much larger than the submix we care about. Nevertheless, the sample has been constructed in such a way, lớn show most of the JSON grammar. The file reads:

,, >, "obj": , "message": "Strings have lớn be in double-quotes." }

In the sample JavaScript, we are only using the array associated with the items key. In contrast khổng lồ ordinary JavaScript, JSON requires us khổng lồ place keys in double-quotes. Additionally, we cannot use trailing commas for specifying objects or arrays. However, as with ordinary JavaScript arrays, we are allowed lớn insert objects of different types.

The Sample Webpage

We already looked at the script and the sample JSON tệp tin. All that’s left is the webpage which provides the parts being used by the JavaScript tệp tin khổng lồ trigger & display the JSON tệp tin.

<html> <head> <meta charset="utf-8"> <title>Request JSON Testtitle> head> <body> <a href="#" id="get-data">Get JSON dataa> <div id="show-data">div> <script src="https://code.jquery.com/jquery-1.9.1.min.js">script> <script src="example.js">script> body> html>

There is not much khổng lồ say here. We use the minified version of jQuery (the old version 1.9.1, which is certainly sufficient for our purposes) from the official webpage. Then we include our script, which is responsible for injecting the logic.

Note: As we are including our JavaScript files in the correct place (just before the closing tag), it no longer becomes necessary lớn use a $(document).ready() callback, because at this point, the document will be ready by definition.


And this is what we kết thúc up with.

The More General Method

As already mentioned, the $.ajax method is the real khuyến mãi for any (not only JSON related) web request. This method allows us to lớn explicitly phối all the options we care about. We can adjust async lớn true if we want this to lớn hotline to lớn run concurrently, i.e., the run potentially at the same time as other code. Setting it lớn false will prsự kiện other code from running while the download is in progress.

$.ajax( }, dataType: "json", success: function (data) });

The overrideMimeType method (which overrides the MIME type returned by the server) is only called for demonstration purposes. Generally, jQuery is smart enough khổng lồ adjust the MIME-type according to the used data type.

Before we go on lớn introduce the concept of JSON validation let’s have sầu short look at a more realistic example. Usually, we will not request a static JSON file, but will load JSON which is generated dynamically (for example as the result of calling an API). The JSON generation is dependent on some parameter(s), which have lớn be supplied beforehvà.

var url = "https://api.github.com/v1/..."; var data = ; $.getJSON(url, data, function (data, status) });

Here we check the status khổng lồ ensure that the result is indeed the object returned from a successful request & not some object containing an error message. The exact status code is API-dependent, however, for most GET requests a status code of 200 is usual.

The data is supplied in the size of an object, which leaves the task of creating the query string (or transmitting the request body) up lớn jQuery. This is the best & most reliable option.

JSON Validation

We should not forget to validate our JSON data! There is an online JSON Validator tool called JSONLint, which can be used to lớn validate JSON files. Unlike JavaScript, JSON is very strict and does not have tolerances, e.g. the aforementioned trailing commas or multiple ways of writing keys (with /, without quotes).

So, let’s discuss some of the most comtháng errors when dealing with JSON.

Comtháng $.getJSON Errors

Silent failures on $.getJSON calls: This might happen if, e.g., jsoncallback=json1234 has been used, while the function json1234() does not exist. In such cases the $.getJSON will silently error. We should therefore always use jsoncallback=? khổng lồ let jQuery automatically handle the initial callbaông xã. In the best case real JSON (instead of JSONP) is used (either by talking with our own server or via CORS). This eliminates a phối of errors potentially introduced by using JSONP.. The crucial question is: Does the VPS / API support JSONP? Are there any restrictions on using JSONP? Uncaught syntax error: Unexpected token (in Chrome) or invalid label (in Firefox). The latter can be fixed by passing the JSON data khổng lồ the JavaScript callbaông chồng. In general, however, this is a strong indicator that the JSON is malformed. Consider using JSONLint as advised above.

The big question is now: How vày we detect if the error actually lies in the transported JSON?

How to fix JSON Errors

There are three essential points that should be covered before starting any JSON-related debugging:

We have lớn make sure that the JSON returned by the hệ thống is in the correct format with the correct MIME-type being used. We can try khổng lồ use $.get instead of $.getJSON as it might be that our server returns invalid JSON. Also if JSON.parse() fails on the returned text we immediately know that the JSON is to blame. We can check the data that is being returned by logging it to the console. This should then be the input đầu vào for further investigations.

Debugging should then commence with the previously mentioned JSONLint tool.


JSON is the de-facto standard format for exchanging text data. jQuery’s $.getJSON() method gives us a nice little helper khổng lồ deal with almost any scenario involving a request for JSON formatted data. In this article we investigated some methods và possiblities that come with this handy helper.

Are there any other best practices for $.getJSON() you cannot live without?