Download json file from url javascript

last modified June 16, 2022

JavaScript read JSON from URL tutorial shows how to read data in JSON format from the provided URL. We use JQuery, Fetch API, and XMLHttpRequest.

URL

A Uniform Resource Locator (URL), is a reference to a web resource that specifies its location on a computer network and a mechanism for retrieving it. A web resource is any data that can be obtained via web, such as HTML documents, PDF files, PNG images, JSON data, or plain text.

A generic URL has the following form:

scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]

The square brackets indicate that the part is optional. A scheme is a way of addressing resources, such as http, ftp, mailto, or file.

The part following two slashes is called the authority part. The authority part contains 1) an optional authentication section of a user name and password, separated by a colon, followed by an at symbol (@) 2) a host, which is either a host name of or an IP address, 3) an optional port number, separated from the host by a colon.

A path is a road to the resource on the host. It may or may not resemble or map exactly to a file system path. Query string is used to add some criteria to the request for the resource. It is often a sequence of key/value pairs. The final part is an optional fragment, which points to a secondary resource, such as a heading. It is separated from the query string by a hash (#).

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json. The JSON filename extension is .json.

In our examples, we use JSON data from http://time.jsontest.com.

{
   "time": "11:27:26 AM",
   "milliseconds_since_epoch": 1494934046126,
   "date": "05-16-2017"
}

The GET request returns this JSON string.

Reading JSON with JQuery

jQuery is a JavaScript library which is used to manipulate DOM. With jQuery, we can find, select, traverse, and manipulate parts of a HTML document.

The JQuery $.getJSON method loads JSON-encoded data from a server using a GET HTTP request.

jQuery.getJSON( url [, data ] [, success ] )

This is the method signature. The url parameter is a string containing the URL to which the request is sent. The data is a plain object or string that is sent to the server with the request. The success is a callback function that is executed if the request succeeds.

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

$.getJSON is a shorthand for the above call.

js_read_json_url.html




JavaScript - read JSON from URL
    



    

In the example, we read JSON data from http://time.jsontest.com. The returned object has three attributes: date, time, and unix epoch.

var text = `Date: ${data.date}
Time: ${data.time}
Unix time: ${data.milliseconds_since_epoch}`

We build the message using the JavaScript template string.

$(".mypanel").html(text);

With JQuery's html method, we append the text to the div tag.

Download json file from url javascript
Figure: Reading JSON from URL with JQuery

In the figure we can see the current date, time, and Unix time.

Reading JSON with Fetch API

Fetch API is interface for fetching resources. It is similar to XMLHttpRequest but its API provides a more powerful and flexible feature set.


The example reads JSON data with Fetch API and prints the returned data to the console. To see the output, we need to activate the developer console of our browser.

The fetch method takes one mandatory argument, the path to the resource we want to fetch. It returns a promise that resolves to the response of the request.

Reading JSON with XMLHttpRequest

XMLHttpRequest API provides client functionality for transferring data between a client and a server. It allows an easy way to retrieve data from a URL without having to do a full page refresh. As a consequence, a web page has to update just a part of the page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.


This example reads JSON data with XMLHttpRequest.

var xhr = new XMLHttpRequest();

A new instance of XMLHttpRequest is created.

xhr.open('GET', url, true);

The open method initializes a request.

xhr.responseType = 'json';

The responseType value defines the response type.

xhr.onload = function() {

    var status = xhr.status;

    if (status == 200) {
        callback(null, xhr.response);
    } else {
        callback(status);
    }
};

In the onload method, we wait for the response from the server.

xhr.send();

The send method sends the request; the request is asynchronous by default.

In this article, we have read JSON data in JavaScript with JQuery, Fetch API, and XMLHttpRequest.

List all JavaScript tutorials.

How can I get JSON data from URL?

In this way, one can easily read a JSON response from a given URL by using urlopen() method to get the response and then use json. loads() to convert the response into a JSON object.

How display JSON data from URL in HTML?

“how to get json data from url in html” Code Answer's.
let url = 'https://example.com';.
fetch(url).
. then(res => res. json()).
. then((out) => {.
console. log('Checkout this JSON! ', out);.
. catch(err => { throw err });.

Can we read JSON data directly from a Web service via HTTP?

JSON Web Services let you access portal service methods by exposing them as a JSON HTTP API. Service methods are made easily accessible using HTTP requests, both from JavaScript within the portal and from any JSON-speaking client.

How do I save a JSON file?

Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as . JSON file, you have to just select the location of the file. Save this answer.