I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:
{"res
You can use XMLHttpRequest() method:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
//console.log("Json parsed data is: " + JSON.stringify(myObj));
}
};
xmlhttp.open("GET", "your_file_name.json", true);
xmlhttp.send();
You can see the response of myObj using console.log statement(commented out).
If you know AngularJS, you can use $http:
MyController.$inject = ['myService'];
function MyController(myService){
var promise = myService.getJsonFileContents();
promise.then(function (response) {
var results = response.data;
console.log("The JSON response is: " + JSON.stringify(results));
})
.catch(function (error) {
console.log("Something went wrong.");
});
}
myService.$inject = ['$http'];
function myService($http){
var service = this;
service.getJsonFileContents = function () {
var response = $http({
method: "GET",
url: ("your_file_name.json")
});
return response;
};
}
If you have the file in a different folder, mention the complete path instead of filename.