How to read a JSON file from a URL in JavaScript
What is JSON?
JSON (JavaScript Object Notation) is the standard design for human-readable data interchange. It is a light-weight, human-readable format used for storing and transporting data. Since JSON works with a tree structure, it looks like an
Read JSON file from URL
There are several online websites that contain JSON data in order to test and apply their algorithms. I will test one such algorithm on JSON data. In JavaScript, there are several methods to read JSON data through a URL such as jqeury, loadJSON methods, etc. In this shot, we’ll look at a simple loadJSON method for better understanding.
- Click here to view the JSON data that you need to load. This JSON data contains information about 100 different posts (as can be seen below). There are 4 different fields namely
userId,id,title, andbody. Theidfield represents the post number.
- Use the following command, as used in the terminal, in the
.jsfile. TheloadJSONfunction is a user-defined method that initiates a new XMLHttpRequest whenever the function is called. This function then checks the status and state of the URL provided to confirm the validity of the JSON data. If there are no errors, parsed JSON data is returned.
The loadJSON function has three parameters:
- The website link that contains the data.
- A function where we define the fate of our data.
- An optional parameter that we sometimes define to ensure data security.
loadJSON("https://jsonplaceholder.typicode.com/posts",myData,'jsonp');
- Define the myData function. When data is read from the website, it is passed directly to the function
myData. As you can see below, the function has aDataparameter. The data read from the website URL is sent to this function in theDataparameter. In this example, we are defining the function to just output the details about the first post:
function myData(Data)
{
console.log(Data[0]);
}
Code
Free Resources