For reading the external Local JSON file (data.json) using javascript, first create your data.json file:
data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
Then,
Mention the path of the json file in the script source along with the javascript file
<script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascript.js"></script>Get the Object from the json file
var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age);
For reading the external Local JSON file (data.json) using javascript, first create your data.json file:
data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';
Then,
Mention the path of the json file in the script source along with the javascript file
<script type="text/javascript" src="data.json"></script> <script type="text/javascript" src="javascript.js"></script>Get the Object from the json file
var mydata = JSON.parse(data); alert(mydata[0].name); alert(mydata[0].age); alert(mydata[1].name); alert(mydata[1].age);
The loading of a .json file from a hard disk is an asynchronous operation, and thus it needs to specify a callback function to execute after the file is loaded.
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);
}
//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
This function also works for loading a .html or .txt files, by overriding the mime type parameter to "text/html", "text/plain", etc.
How to import json files in js
How do I load a JSON file? - JavaScript - Kotlin Discussions
[deleted by user]
Using ONLY normal, pure JS, how do I read a json file
Videos
Hi, is there any way to import .json file in to a js file like (import data from './data.json') ? I've tried that and also added <script type="module"/> in my html also still it was not working for me, I'd greatly appreciate to learn how to import json in my js file.
Thankyou in advance ;)