Read JSON data on the Web with JavaScript

JSON is a data format method based on object literal in JavaScript, and it is often used because of its simplicity and high affinity with JavaScript. This section explains how to read JSON format data on the Web from JavaScript.

Loading JSON with XMLHttpRequest

XMLHttpRequest () is an object for sending requests to the server using HTTP. I will explain the flow of processing to acquire JSON data on the Web using XMTHttpRequest (). Let’s see the following sample program.

First, assume that the following JSON file is placed on any server.


{   "item_code": "001",   "item_name": "apple",   "item_price": "100" }


<input type="button"value="Receive the JSON file" onclick="getJSON()">


function getJSON() {
var req = new XMLHttpRequest();    // XMLHttpRequest init Object   
req.onreadystatechange = function() {    // XMLHttpRequest  
if(req.readyState == 4 && req.status == 200){       
} };"GET", "", false);   req.send(null);   

This program is a program that retrieves JSON files from the specified URL and displays the contents as character strings. Let’s see the flow of processing below.

First, create an XMLHttpRequest () object. onreadystatechange is an event handler that is called when the state of the XMLHttpRequest () object changes. The ready state representing the state of the object has a state from 0 to 4, and 4 indicates the state where the response from the server has been received.

The response code from the server is included in the status, and 200 indicates the success of the communication (for example, if it is 404, the response code is that the file does not exist). When the communication is successful, the response sent from the server is stored in responsT as a character string.

open () specifies the URL of the HTTP method (GET in this case) and the server (here the server where the JSON file is located) to access. Send requests to the server with send (). If you do not need to send data with GET method etc, specify null as argument.

As a result, the contents of the above sample.json are displayed as alerts as character strings.

Notes on server communication

JavaScript has security constraints called security policies that are security-impossible to communicate with servers other than the server that downloaded JavaScript programs. For this reason, JavaScript program files and JSON files do not work unless they are on the same scheme (the protocol part of the URL) on the server (http and https are also distinguished).



Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?