What is json-format?
The json-format npm package is a utility for formatting JSON strings in a readable and pretty-printed manner. It allows developers to easily convert JSON objects into a human-readable format with customizable indentation and other formatting options.
What are json-format's main functionalities?
Basic Formatting
This feature allows you to format a JSON object into a readable string with default settings.
const jsonFormat = require('json-format');
const jsonObject = { name: 'John', age: 30, city: 'New York' };
const formattedJson = jsonFormat(jsonObject);
console.log(formattedJson);
Custom Indentation
This feature allows you to customize the indentation of the formatted JSON string. In this example, the indentation is set to 4 spaces.
const jsonFormat = require('json-format');
const jsonObject = { name: 'John', age: 30, city: 'New York' };
const config = { type: 'space', size: 4 };
const formattedJson = jsonFormat(jsonObject, config);
console.log(formattedJson);
Customizing Key Order
This feature allows you to specify the order of keys in the formatted JSON string. In this example, the keys are ordered as 'city', 'name', and 'age'.
const jsonFormat = require('json-format');
const jsonObject = { name: 'John', age: 30, city: 'New York' };
const config = { type: 'space', size: 2, reorderKeys: ['city', 'name', 'age'] };
const formattedJson = jsonFormat(jsonObject, config);
console.log(formattedJson);
Other packages similar to json-format
prettyjson
The prettyjson package provides similar functionality for formatting JSON objects into a readable string. It offers options for customizing colors and indentation. Compared to json-format, prettyjson focuses more on colorized output for better readability in the terminal.
json-stringify-pretty-compact
The json-stringify-pretty-compact package is another alternative for formatting JSON strings. It aims to produce compact and pretty-printed JSON output. Unlike json-format, it focuses on minimizing the output size while maintaining readability.
json-beautify
The json-beautify package provides functionality to beautify JSON strings with customizable indentation and sorting options. It is similar to json-format but offers additional features like sorting keys alphabetically.
json-format
Change for using with npm modules. original version.
Instaling
npm install json-format
Usage
var jsonFormat = require('./');
var fs = require('fs');
var obj = {
a: 1,
b: 2
}
fs.writeFile('example.json', jsonFormat(obj), function(err){
if (err) throw err;
console.log('saved');
});
Result
{
"a": 1,
"b": 2
}