- Read JSON file with Javascript
- Read JSON file in Javascript by passing file using HTML input
- Read Local JSON file in Javascript by passing file location
- Read External JSON file in Javascript
- Parsing JSON in Javascript
- 3 Ways To Read JSON In JavaScript
- 1. Using fetch() method
- 2. Using AJAX
- 3. Using jQuery
- Conclusion
Read JSON file with Javascript
In previous article, I have mentioned, how to read excel file in javascript, read pdf using javascript, now in this article, I have mentioned, how to read json file with javascript or you can say how to read json in javascript and how to parse json in javascript.
Let’s consider this is our sample JSON file which we will be using in this article:
Read JSON file in Javascript by passing file using HTML input
In this example, we will pass json file using input type = file and then we will be reading file in javascript with FileReader() , so here is the example for this
and javascript function which will read file on input file change:
document.getElementById("jsonfileinput").addEventListener("change", function() < var file_to_read = document.getElementById("jsonfileinput").files[0]; var fileread = new FileReader(); fileread.onload = function(e) < var content = e.target.result; var intern = JSON.parse(content); // parse json console.log(intern); // You can index every object >; fileread.readAsText(file_to_read); >);
In the above code, we are reading file using FileReader , once file is loaded in fileread object, we will be using JSON.parse to Parse the JSON
Output which looks something like this in browser
Here is the working fiddle
Read Local JSON file in Javascript by passing file location
function readTextFile(file, callback) < var rawFile = new XMLHttpRequest(); rawFile.overrideMimeType("application/json"); rawFile.open("GET", file, true); rawFile.onreadystatechange = function() < if (rawFile.readyState === 4 && rawFile.status == "200") < callback(rawFile.responseText); >> rawFile.send(null); > calling above function readTextFile("/Users/ct/Desktop/example.json", function(text)< var data = JSON.parse(text); //parse JSON console.log(data); >);
In the above code, we are loading json from harddisk, which is an asynchronous operation and thus it needs to specify a callback function to execute after the file is loaded.
Read External JSON file in Javascript
In this method, we will be passing JSON in a file from different location, by using Fetch API, as shown in the below code
fetch("https://newexample.s3.ir-thr-at1.arvanstorage.com/example.json") .then(response => response.json()) .then(json => console.log(json));
In the above code, we are using fetch API, and passing location in fetch, once we have got the response, we are using console.log to print it, we can also using JSON.parse to parse the JSON and use it.
Suppose, we simply want to get the «title» value from above JSON, then we can print it as below
fetch("https://newexample.s3.ir-thr-at1.arvanstorage.com/example.json") .then(response => response.json()) .then(json => console.log(json.glossary.title));
OR Using jQuery $.getJSON, you can have below code
var url = "https://newexample.s3.ir-thr-at1.arvanstorage.com/example.json"; $.getJSON(url, function (data) < $.each(data, function (key, model) < console.log(key); >) >);
Parsing JSON in Javascript
Although with the above examples, I have mentioned how we can parse JSON in javascript, here is the simple example of it
let contactJSON = ''; let contact = JSON.parse(contactJSON); console.log(contact.name + ", " + contact.age);
In the above code, you can see, we have taken simple JSON example and assigned it to variable, and used JSON.parse to parse it using variable, then using .name or .age to get it’s value.
If you are getting values as an array or list inside JSON, then you can loop these values using $.each.
3 Ways To Read JSON In JavaScript
A big part of data transactions between client and server is JSON. In this article, we will discuss 3 different ways to read JSON file in JavaScript.
JSON is used to store data in a structured way. You can store the data of your customer in a JSON file and then read it in JavaScript.
A JSON file can be stored in a server or in a client. We will see how to read them both.
1. Using fetch() method
The fetch() method is used to send and receive data from a server. It can be used to read JSON files stored in a server or in the client.
It is a core part of JavaScript and you do not need to import any library to use it.
Here, url is the URL of the JSON file. It can be a local file or a remote file.
The fetch() method returns a Promise object which is used to get the response from the server.
Here is a working example:
// read local JSON file in javascript fetch("./lib/examples/employee.json") .then(function (response) < return response.json(); >) .then(function (data) < console.log(data); >)
Press the run button and you will see that the JSON file is fetched and displayed in the console.
If your JSON file is in a remote server then you can follow the same steps just pass the correct URL of the JSON file in the fetch() method.
// read remote JSON file in javascript fetch("https://jsonplaceholder.typicode.com/users") .then(function (response) < return response.json(); >) .then(function (data) < for (let i = 0; i < data.length; i++) < console.log(data[i]); >>)
The above example will fetch the data from the remote server and display it in the console.
2. Using AJAX
AJAX is used to send and receive data from a server. You can use it to request a JSON file from a server and the server will send the data of the JSON file back to the client.
Note : AJAX supports http protocol only. It will not work for local files. To get the local files you need to run a server locally and you will be able to access local files.
Let’s see how to use AJAX to read JSON files in JavaScript.
// reading JSON file using AJAX // create a new XMLHttpRequest object var xhr = new XMLHttpRequest(); // open a connection xhr.open("GET", "./lib/examples/employee.json", true); // send the request xhr.send(); // handle the response xhr.onreadystatechange = function () < if (this.readyState == 4 && this.status == 200) < console.log(this.responseText); >>
- Create a new XMLHttpRequest object. This is the object that will be used to send and receive data from the server.
- Open a connection. Use the open() method to open a connection. The first parameter is the request type (GET or POST). The second parameter is the URL of the file (JSON here). The third parameter is true or false. If true then the request will be asynchronous otherwise it will be synchronous.
- Send the request. Use send() method to send the request.
- Handle the response. Use onreadystatechange event to handle the response. The onreadystatechange event is triggered when the readyState changes. The readyState is a number and it can be one of the following values:
- 0 : request not initialized
- 1 : server connection established
- 2 : request received
- 3 : processing request
- 4 : request finished and response is ready
3. Using jQuery
jQuery is a JavaScript library that is used to make JavaScript easier to use. It provides many useful methods to make your life easier.
To get JSON you can use the $.getJSON() method which uses AJAX behind the scenes to get the JSON file from the server.
Since it uses AJAX, it will not work for local files.
Here is a working example of $.getJSON() method:
// read local JSON file using jQuery $.getJSON("./lib/examples/employee.json", function (data) < console.log(data); >)
Conclusion
We have seen 3 different ways to read JSON file in JavaScript. You can use the same method to read XML files as well and do something useful.