Formatting JSON in Node.js using the prettyjson module

The following example shows how you can format objects in Node.js using the prettyjson module.

First, create a package.json file, and paste the following contents:

{
  "name": "prettyjson-test",
  "description": "prettyjson test case",
  "private": true,
  "version": "0.0.1",
  "engines": {
    "node": "0.8.x",
    "npm": "1.1.x"
  }
}

Next, create an app.js file in the same directory as the package.json file created earlier and paste the following contents:

#!/usr/bin/env node

var packagejson = require("./package.json");

console.log(prettyJSON(packagejson));

function prettyJSON(data) {
    return JSON.stringify(data);
}

Now, if we run the app.js file from the Terminal (node app.js) we should see the following output:

{"name":"prettyjson-test","description":"prettyjson test case","private":true,"version":"0.0.1","engines":{"node":"0.8.x","npm":"1.1.x"}}

As you can see, the JSON packet is stringified and fairly compact (and not very readable).

Next lets modify our prettyJSON() function to make the the JSON packet more readable by passing a couple more optional parameters. Change the prettyJSON() method to the following:

function prettyJSON(data) {
    return JSON.stringify(data, null, "    ");
}

If we run the app.js file again, we should now see the following output:

{
    "name": "prettyjson-test",
    "description": "prettyjson test case",
    "private": true,
    "version": "0.0.1",
    "engines": {
        "node": "0.8.x",
        "npm": "1.1.x"
    }
}

Much better!

Next, lets look at converting this example to use the prettyjson module.

Install the prettyjson module using the following command from the command line:

npm install prettyjson --save

This command will install the prettyjson module and add it as a dependency to our package.json file.

Modify the app.js file to use the prettyjson module by replacing the existing code with the following:

#!/usr/bin/env node

var prettyjson = require("prettyjson");
var packagejson = require("./package.json");

console.log(prettyJSON(packagejson));

function prettyJSON(data) {
    return prettyjson.render(data);
}

If we run the app.js file from the Terminal (node app.js) again we should now see the following output:

name:         prettyjson-test
description:  prettyjson test case
private:      true
version:      0.0.1
dependencies: 
  prettyjson: ~0.6.0
engines: 
  node: 0.8.x
  npm:  1.1.x

Note: The output looks better in the Terminal console as the properties are nicely colored.

For more information, see http://rafeca.com/prettyjson/.

Leave a Reply

Your email address will not be published.