javascript json nodejs code example
Example 1: Working with JSON in Node.js
/*
This code comes from Vincent Lab
And it has a video version linked here: https://www.youtube.com/watch?v=dR--FnRoYh0
*/
// Import dependencies
const fs = require("fs");
// Load the config
const config = require("./config.json");
// Show the config
console.log(config);
// Modify the config
config.apiKey = "gj3j#4K321hIO"; // 2i3f2399g23y43q9o
// Saved the config
fs.writeFile("./config.json", JSON.stringify(config), function (err, file) {
if (err) throw err;
console.log("Saved!");
});
Example 2: javascript parse json
var jsonPerson = '{"first_name":"billy", "age":23}';
var personObject = JSON.parse(jsonPerson); //parse json string into JS object
Example 3: json parse returns object
var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a string
var parsed = JSON.parse(str); // an *array* that contains the user
var user = parsed[0]; // a simple user
console.log(user.UserName); // you'll get xxx
console.log(user.Rolename); // you'll get yyy