3.8 Working with JSON

Last time we saw how Yargs greatly reduced our difficulty in dealing with arguments in form of key-value pair. Today we will learn how to store information in the file system, so when users read their notes, they really fetch their data back.

JSON

JSON stands for JavaScript Object Notation. This allows us to represent any JavaScript Object as a String.

Convert Object to String

var obj = {
name: "Jude"
};
var stringObj = JSON.stringify(obj);
console.log(typeof stringObj);
console.log(stringObj);

Output:

jude@jude-ThinkPad-S5:~/Desktop/n-3-6-getting-input/playground$ node json.js
string
{"name":"Jude"}

Convert String to Object

var personString = '{"name":"Jude", "age": 19}'
// personString.name; // WRONG
var person = JSON.parse(personString);
console.log(typeof person);
console.log(person);

Output:

var personString = '{"name":"Jude", "age": 19}'
// personString.name; // WRONG
var person = JSON.parse(personString);
console.log(typeof person);
console.log(person);

Store in File

const fs = require('fs');
var originalNote = {
title: "some title",
body: "some body"
}
var originalNoteString = JSON.stringify(originalNote);
fs.writeFileSync('notes.json', originalNoteString);
var noteString = fs.readFileSync('notes.json');
var note = JSON.parse(noteString);
console.log(typeof note);
console.log(note.title);

Output:

jude@jude-ThinkPad-S5:~/Desktop/n-3-6-getting-input/playground$ node json.js
object
some title

If someone adds a note, we use readFileSync to read everything from notes.json, modify the notes array, and then use writeFileSync simply to override everything for updates.