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 cannot make a AJAX call to a local resource as the request is made using HTTP.
A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.
In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON()
:
http://api.jquery.com/jQuery.getJSON/
When in Node.js or when using require.js in the browser, you can simply do:
let json = require('/Users/Documents/workspace/test.json');
console.log(json, 'the json obj');
Do note: the file is loaded once, subsequent calls will use the cache.
Very simple.
Rename your json file to ".js" instead ".json".
<script type="text/javascript" src="my_json.js"></script>
So follow your code normally.
<script type="text/javascript">
var obj = JSON.parse(contacts);
However, just for information, the content my json it's looks like the snip below.
contacts='[{"name":"bla bla", "email":bla bla, "address":"bla bla"}]';
You can import It like ES6 module;
import data from "/Users/Documents/workspace/test.json"
Just use $.getJSON and then $.each to iterate the pair Key /value. Content example for the JSON file and functional code:
{
{
"key": "INFO",
"value": "This is an example."
}
}
var url = "file.json";
$.getJSON(url, function (data) {
$.each(data, function (key, model) {
if (model.key == "INFO") {
console.log(model.value)
}
})
});
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.