node js JSON code example
Example 1: node js return json
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);
Example 2: Working with JSON in Node.js
const fs = require("fs");
const config = require("./config.json");
console.log(config);
config.apiKey = "gj3j#4K321hIO";
fs.writeFile("./config.json", JSON.stringify(config), function (err, file) {
if (err) throw err;
console.log("Saved!");
});
Example 3: js parse json
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
console.log(obj.result);
Example 4: js string to json
var obj = JSON.parse("{no:'u',my:'sql'}");