- 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
- How to Fetch and Display JSON Data in HTML Using JavaScript
- Fetching the JSON data
- Displaying the JSON data
- Step 1 – Get the div element from the body
- Step 2 – Loop through every object in our JSON object
- Step 3 – Append each person to our HTML page
- Why use V anilla JavaScript?
- Recent Posts
- About Us
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.
How to Fetch and Display JSON Data in HTML Using JavaScript
In this tutorial, I will show you how to fetch and display data from a JSON file using vanilla JavaScript.
So how will we achieve this?
First, we will fetch the JSON data by using the fetch API. This will return a promise with our JSON data. Then we will append the data dynamically by creating HTML elements on the fly. We will then append our JSON data to those elements.
Getting JSON data from an API and display it on a web page is a common thing you will do quite often. I have created similar posts on the big frameworks like React, Vue and Angular. Check it out if you are using any of those frameworks.
First, create a people.json file and fill it with the following data:
We will save this file in the same directory as our index.html file.
Fetching the JSON data
To be able to display this data in our HTML file, we first need to fetch the data with JavaScript.
We will fetch this data by using the fetch API. We use the fetch API in the following way:
fetch(url) .then(function (response) < // The JSON data will arrive here >) .catch(function (err) < // If an error occured, you will catch it here >);
The url parameter used in the fetch function is where we get the JSON data. This is often an http address. In our case it is just the filename people.json . We don’t have to drill down to any directory since the json file is in the same directory as our index.html .
The fetch function will return a promise. When the JSON data is fetched from the file, the then function will run with the JSON data in the response.
If anything goes wrong (like the JSON file cannot be found), the catch function will run.
Let us see how this will look in out example:
fetch('people.json') .then(function (response) < return response.json(); >) .then(function (data) < appendData(data); >) .catch(function (err) < console.log(err); >);
Here we are fetching our people.json file. After the file has been read from disk, we run the then function with the response as a parameter. To get the JSON data from the response, we execute the json() function.
The json() function also returns a promise. This is why we just return it and chain another then function. In the second then function we get the actual JSON data as a parameter. This data looks just like the data in our JSON file.
Now we can take this data and display it on our HTML page. Notice that we are calling a function called appendData . This is where we create the code which will append the data to our page.
Notice that in our catch function, we are just writing the error message to out console. Normally you would display an error message to the user if something went wrong.
Displaying the JSON data
Before we display our JSON data on the webpage, let’s just see how the body of our index.html file looks like.
Pretty simple right? We have just a simple div with the id myData . Our plan is to fill our JSON data inside this div dynamically.
There are several ways to display the data in our HTML. We could create a table and make it look really good with nice styling. However, we will do this in a simple and ugly way.
Our goal is to just simply display the full name of the people in our JSON file.
Step 1 – Get the div element from the body
Remember the div with the myData id from our index.html ? We want to fetch that div using JavaScript. We need this because we are going to fill the div with the people in our JSON file.
This is how we will do it:
var mainContainer = document.getElementById("myData");
We get the element by executing the getElementByID function. This will find the element with the id myData . This is vanilla JavaScript and this is how we did front-end development in the “old” days :).
Step 2 – Loop through every object in our JSON object
Next step is to create a simple loop. We can then get every object in our list of JSON object and append it into our main div.
Step 3 – Append each person to our HTML page
Inside the for-loop we will append each person inside its own div. This code will be repeated three times for each person.
First, we will create a new div element:
var div = document.createElement("div");
Next we will fill that div with the full name from our JSON file.
div.innerHTML = 'Name: ' + data[i].firstName + ' ' + data[i].lastName;
Lastly, we will append this div to our main container:
mainContainer.appendChild(div);
That’s it. Now we have finished appending the JSON data to our index.html page. The full appendData function looks like this:
When we run our index.html page, it will look something like this:
Not the most beautiful application, but it got the job done.
Let us look at the entire HTML file with the JavaScript:
fetch('people.json') .then(function (response) < return response.json(); >) .then(function (data) < appendData(data); >) .catch(function (err) < console.log('error: ' + err); >); function appendData(data) < var mainContainer = document.getElementById("myData"); for (var i = 0; i < data.length; i++) < var div = document.createElement("div"); div.innerHTML = 'Name: ' + data[i].firstName + ' ' + data[i].lastName; mainContainer.appendChild(div); >>
Try to copy and paste this in your own editor. As an exercise, you can try to style the output to look nicer. Remember to include the people.json file as well. This file must be in the same directory as your index.html file for this to work.
Why use V anilla JavaScript?
You might be wondering what is the point of creating this in vanilla JavaScript. Doesn’t modern web application use frameworks and libraries like Angular, ReactJS or VueJS?
Well, yeah, you are probably right, most of the time. But some web pages are just static with very little logic.
If you just want to tweak some minor parts of the website, it might be overkill to include big libraries which will slow down the site.
Besides, frameworks and libraries come and go. Good old vanilla JavaScript is here to stay. So take every opportunity to learn it, you don’t know when you might need it.
I am a full-stack web developer with over 13 years of experience. I love learning new things and are passionate about JavaScript development both on the front-end and back-end.
Recent Posts
In this article, we will look at sorting an array alphabetically in JavaScript. We will cover both arrays with strings and arrays with objects. Sorting an Array with Strings When sorting an.
In this tutorial, I will show you how to programmatically set the focus to an input element using React.js and hooks. We will use two hooks, useRef and useEffect. Set up the Project All you.
About Us
We are a team of passionate web developers with decades of experience between us.
This site will focus mostly on web development. We love writing and we want to share our knowledge with you.
Hope you’ll enjoy and have fun coding!