How to Get JSON From URL in jQuery and AJAX

Last Updated on April 20, 2022 by Roshan Parihar

In this tutorial, learn how to get JSON from URL using jQuery or AJAX. The short answer is to use the $.getJSON() function in jQuery and $.ajax() in AJAX to get JSON data.

Support that you have a JSON file containing the data as shown below. It contains the name and email of a person that you have to get using jQuery and AJAX.

So, let’s find out how you can get JSON data from the specified URL with the examples given below.

How to Get JSON Data From URL Using jQuery

To get the JSON data from the specified URL on the button click, you have to use the $.getJSON() function in jQuery. The below example shows the URL of the JSON file and the data retrieved from it to show in jQuery alert.

Test it Live

As the JSON file contains the data within the square bracket ([]), you have to use the square bracket with the data to get the required results.

Now, when someone clicks on the button, the person will get the name and the email of the person in the alert.

Using AJAX to Get JSON Data From URL or JSON File

If you want to get the JSON data using AJAX, you have to use the $.ajax() function. You also have to specify the type: "GET" and the type of the data using dataType: 'json'. The result of the function will be delivered within the success as shown below.

Test it Live

This will give the same result as you got in the previous example. You just need to remember that you have to specify that you are going to get the JSON data using dataType.

Get Second Level JSON Data Inside File

In addition to the above examples, you can also get the second-level data within the JSON file using any of the above functions. Let’s find out how to get the second level data using the $.getJSON() function.

The second level of data in the JSON file is showing the address of the person. You have to fetch the address using the jQuery function.

So, let’s find out how you can get the second-level JSON data with the example given below. You have to use the example given below to get your data.

Test it Live

When you click the button given above, you will get the name, email, and country of the person using jQuery getJSON() method.

You May Also Like to Read

I hope you like this post on how to get JSON data using jQuery or AJAX.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.