We use JSON.parse to interpret strings of JSON data into JavaScript objects. For example:

function Student(name) {
    this.name = name;

let P422F20 = {
    section: 12381,
    instructor: 'Chris Sexton',
    book: 'Node.js, MongoDB and Angular',
    students: [
        new Student('Jimmy Student'),
        new Student('Jenny Student')
    startDate: new Date('2020-08-24')

console.log(JSON.stringify(P422F20, null, 2));

let obj = JSON.parse('{"name": "foo"}');
obj.name = obj.name + " Bar";
const fs = require('fs');

let packagePath = '../package.json';

fs.readFile(packagePath, (err, data) => {
    if (err) throw err;

    let packageStr = data.toString();
    let package = JSON.parse(packageStr);

    // console.log(package);

    package.author = 'P422 Class';
    console.log('package.scripts.start: %s', package.scripts.start);
    console.log('package["scripts"]["start"]: %s', package["scripts"]["start"]);

    packageStr = JSON.stringify(package, null, 2);

    fs.writeFile(packagePath, packageStr, (err) => {
        if (err) throw err;
        console.log('Done writing package.json out!');


NPM browsing

We really want to vet any dependency that we add to our project. npmjs.com is a great resource, but anybody can publish anything to it. Be sure to select projects that are popular, high quality, and update frequently!

Useful links:

We will return to schema validation at the end of REST data to ensure that valid data is passed between the server and the client.

Other options

Hey, what if you don’t want JSON!? Are you ill?

It’s totally reasonable to use libraries to read and write data in different formats. One such example is XML. But seriously, let’s not do that. Protobuf is Google’s streaming serialization language for data, and it’s totally reasonable to read and write protobuf from Node and client-side JS. Have a look at the following pages to see some examples of protobufs in action.