Comprehensive Guide to prettyjson for JavaScript Developers

Introduction

prettyjson is an incredibly useful Node.js library that formats JSON data and JSON-like structures in a more readable and colored CLI output. Whether you are debugging or just want more readable JSON data, prettyjson makes it easy. In this comprehensive guide, we will explore dozens of useful prettyjson API functions with code snippets and implement an app example using these APIs.

Installation

npm install prettyjson

APIs and Code Snippets

prettyjson.render

This is the primary method used to render JSON data in a pretty format.

const prettyjson = require('prettyjson');
const data = {
  name: "John Doe",
  age: 29,
  location: {
    city: "San Francisco",
    state: "California"
  }
};

console.log(prettyjson.render(data));

prettyjson.renderString

Renders a JSON string in pretty format.

const jsonString = '{"name":"John Doe","age":29,"location":{"city":"San Francisco","state":"California"}}';

console.log(prettyjson.renderString(jsonString));

prettyjson.setColors

Customize the colors used in the output.

prettyjson.setColors({
  keys: 'blue',
  dash: 'green',
  string: 'yellow'
});

console.log(prettyjson.render(data));

Implementing an App example

Let’s create a simple Node.js app that fetches user data from an API and prints it in a readable format using prettyjson.

const prettyjson = require('prettyjson');
const fetch = require('node-fetch');

async function fetchUserData() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  const userData = await response.json();

  console.log(prettyjson.render(userData));
}

fetchUserData();

By following the above guidelines and utilizing the powerful APIs offered by prettyjson, you can significantly enhance the readability and debugging process of your JSON data in Node.js applications.

Hash: 9ba96f4cfc928d48b775d7254ed933a2136b0692795d156a391e132a13919c71

Leave a Reply

Your email address will not be published. Required fields are marked *