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 XMLExtensible Markup Language (XML) a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.. For developers, XML is shorter to write and very easy to comprehend due to its many built-in features. XML is mostly used when data is sent from a server to a web page.

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.

  1. 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, and body. The id field represents the post number.
svg viewer
  1. Use the following command, as used in the terminal, in the .js file. The loadJSON function 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');
  1. 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 a Data parameter. The data read from the website URL is sent to this function in the Data parameter. 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

Console
Copyright ©2024 Educative, Inc. All rights reserved