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);

// > {"a":1}

Example 2: 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 3: js parse json

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

console.log(obj.count);
// expected output: 42

console.log(obj.result);
// expected output: true

Example 4: js string to json

var obj = JSON.parse("{no:'u',my:'sql'}");//returnes {no:'u',my:'sql'}