js load json file code example
Example 1: HOW WRITE AND SAVE JSON FILE IN NODEJS
'use strict';
const fs = require('fs');
let student = {
name: 'Mike',
age: 23,
gender: 'Male',
department: 'English',
car: 'Honda'
};
let data = JSON.stringify(student, null, 2);
fs.writeFile('student-3.json', data, (err) => {
if (err) throw err;
console.log('Data written to file');
});
console.log('This is after the write call');
Example 2: java load .json file
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class JsonParsing {
public static void main(String[] args) throws Exception {
InputStream is =
JsonParsing.class.getResourceAsStream( "sample-json.txt");
String jsonTxt = IOUtils.toString( is );
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
}
}
Example 3: read json file into object javascript
fs.readFile(filePath, function (error, content) {
var data = JSON.parse(content);
console.log(data.collection.length);
});
Example 4: 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 5: 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);
}
});