open json file javascript code example
Example 1: read json file into object javascript
fs.readFile(filePath, function (error, content) {
var data = JSON.parse(content);
console.log(data.collection.length);
});
Example 2: read json from file js
const fs = require('fs');
fs.readFile('./customer.json', 'utf8', (err, jsonString) => {
if (err) {
console.log("File read failed:", err)
return
}
console.log('File data:', jsonString)
})
Example 3: parse local json file
let object;
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "local/path/file.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", function() {
if (this.readyState === this.DONE) {
object = JSON.parse(this.response);
}
});