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
I liked what Stano/Meetar commented above. I use it to read .json files. I have expanded their examples using Promise. Here is the plunker for the same. https://plnkr.co/edit/PaNhe1XizWZ7C0r3ZVQx?p=preview
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("DATA.json", function(text){
// var data = JSON.parse(text);
// console.log(data);
// });
var task1 = function (){
return new Promise (function(resolve, reject){
readTextFile("DATA.json", function(text){
var data = JSON.parse(text);
console.log('task1 called');
console.log(data);
resolve('task1 came back');
});
});
};
var task2 = function (){
return new Promise (function(resolve, reject){
readTextFile("DATA2.json", function(text){
var data2 = JSON.parse(text);
console.log('task2 called');
console.log(data2);
resolve('task2 came back');
});
});
}
Promise.race([task1(), task2()])
.then(function(fromResolve){
console.log(fromResolve);
});
The reading of JSON can be moved into another function, for DRY; but the example here is more of showcasing how to use promises.
You can use d3.js to import JSON files. Just call d3 on your html body:
<script src="https://d3js.org/d3.v5.min.js"></script>
Then put this on your js scripts:
d3.json("test.json").then(function(data_json) {
//do your stuff
})
I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:
// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) =>
new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.onload = resolve;
request.onerror = reject;
request.overrideMimeType("application/json");
request.open(options.method, file, true);
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === "200") {
resolve(request.responseText);
}
};
request.send(null);
});
You can call it like this:
readFileP('<path to file>')
.then(d => {
'<do something with the response data in d.srcElement.response>'
});
As many people mentioned before, this doesn't work using an AJAX call. However, there's a way around it. Using the input element, you can select your file.
The file selected (.json) need to have this structure:
[
{"key": "value"},
{"key2": "value2"},
...
{"keyn": "valuen"},
]
<input type="file" id="get_the_file">
Then you can read the file using JS with FileReader():
document.getElementById("get_the_file").addEventListener("change", function() {
var file_to_read = document.getElementById("get_the_file").files[0];
var fileread = new FileReader();
fileread.onload = function(e) {
var content = e.target.result;
// console.log(content);
var intern = JSON.parse(content); // Array of Objects.
console.log(intern); // You can index every object
};
fileread.readAsText(file_to_read);
});
If you are using local files, why not just packade the data as a js object?
data.js
MyData = { resource:"A",literals:["B","C","D"]}
No XMLHttpRequests, no parsing, just use MyData.resource
directly
So, if you are planning to go with "Apache Tomcat" for hosting your JSON file,
1> After starting up the server, verify that your Apache Tomcat is up and running by going to this url: "localhost:8080" -
2> Next, go to the "webapps" folder - "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps". And, create a project folder or copy your project folder.
3> Paste your json file over there.
4> And that's it. You are done! Just go to - "http://localhost:8080/$project_name$/$jsonFile_name$.json"