Get JSON Data from a URL in JavaScript

In this article, I will tell you how to get JSON data from a URL in JavaScript. So basically JSON Stands for JavaScript Object Notation is a text-based representation of structured data. It is open, lightweight, used for transmitting data in web applications and even storing data in some cases. To get JSON data from a URL In JavaScript we will use the fetch method over here.

Now, let’s see how it happens…

Fetch Method

fetch is a function and as this is asynchronous in nature we can do multiple operations at the same time that is time-independent so it will run in the background and let you know when it finishes so we get JSON data easily. also, we can Insert, Update, Read and Delete data on the server.

Syntax: Simply write fetch method using round brackets.

fetch();

suppose I want to read the data of a file from the server, then I will give the path of that file inside the fetch method (the path can be of any server-side language). so basically it returns us the promise.

fetch(file/URL); -------->promise

PROMISE: Used to handle asynchronous operations. It is an object that determines what happens after the event has happened

Whenever a promise is returned, It is either successful or it fails.

  • CASE (I): IN first, we use then function with success. This also returns the promise.
    fetch(URL) .then();  --------->promise

whatever data we get from fetch we will send it under then function that is the response. Here, response is a variable you can
give any name of variable. We do not print the variable, we return it. Now this data is in the form of JSON

    fetch(URL) .then((response)=>response.JSON());
  • CASE(II): In the second case, We take the scenario of fail. If our server does not respond, We will get an error. In case of error, We use

    CATCH method.

    fetch(URL) .catch((error)=>console.log("error"));

So let’s see our code:

<script>
    fetch("https://jsonplaceholder.typicode.com/users")
    .then((response)=>response.JSON()) 
    .then((data)=>console.log(data)) 
    .catch((error)=>console.log("error"));
</script>

Now here I bring fake data of JSON for that we can copy the URL of any data from JSON_PLACE_HOLDER site (you can use other sites also but I recommend this).

https://jsonplaceholder.typicode.com/

note: fetch method works on live server.

Also read: How to fetch data from public API using JavaScript?

I hope, this article will be going to help you and write a comment if you are facing any difficulty.

Leave a Reply

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