How To Read JSON file with JavaScript

How To Read JSON file with JavaScript;- in this post You will learn How To read JSON Files using Java script Follow Along This Article To Find Out.

Read JSON file with JavaScript

In previous articles, We mentioned, how to read excel file in javascript, read pdf using javascript, now in this article, We have mentioned, how to read json file with 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:

{
    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
				"SortAs": "SGML",
				"GlossTerm": "Standard Generalized Markup Language",
				"Acronym": "SGML",
				"Abbrev": "ISO 8879:1986",
				"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
                    },
					"GlossSee": "markup"
                }
            }
        }
    }
}

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

<input type="file" id="jsonfileinput" />

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

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 = '{"name":"John Doe","age":"11"}';
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.