Skip to content

Utility function to beautify JSON string...like JSON.stringify() but better

License

Notifications You must be signed in to change notification settings

ezze/node-perfect-json

Repository files navigation

node-perfect-json

NPM version CircleCI codecov Downloads/month License

Utility function to beautify JSON string...like JSON.stringify() but better

Installation

npm install perfect-json

or

yarn add perfect-json

Usage

perfectJson(obj, options)
  • obj — JSON to beautify;
  • options — optional parameters:
    • indent — count of indentation spaces (defaults to 2);
    • compact — tells whether close and open brackets of object array items must be placed on the same line (defaults to true);
    • singleLine — tells whether values of object properties must be placed on a single line, it can be of boolean type or a function returning a boolean result and being invoked for each property of an object recursively — the function receives an object argument with the following properties:
      • key — name of the current property (zero-based index in case of array);
      • value — value of the current property;
      • path — array consisting of names of all ascendant properties including the current one;
      • items — array of references to all ascendant objects and arrays;
      • line — stringified array or object value placed on a single line;
      • depth — zero-based depth level (equals to path.length and items.length);
      • indent — count of indentation spaces per level ((depth + 1) * indent results in a summary indentation on a given level).
    • maxLineLength — places objects and arrays on a single line if resulting line's length is less than or equal to specified value;
    • arrayMargin — characters after opening and before closing array brackets when array is placed on a single line (defaults to empty string meaning no gap: ["Javascript", "Node.js", "ES6"]);
    • objectMargin — characters after opening and before closing object brackets when object is placed on a single line (defaults to ' ' meaning a gap: { "node": "14.0.0", "eslint": true, "babel": true, "typescript": false });
    • split — function to split the resulting JSON into several nested JSONs, it accepts the same properties as singleLine function excepting line and should return a string placeholder to replace the current property by; JSON parts replaced by placeholders are stored in a separate object (where keys are placeholders) that can be accessed in splitResult function;
    • splitResult — function being called at the end of transformation with an object of splitted JSONs as an argument.

Basic example

Just pass an object to stringify:

const perfectJson = require('perfect-json');
console.log(perfectJson({
  name: 'Dmitriy',
  surname: 'Pushkov',
  skills: ['JavaScript', 'Node.js', 'ES6'],
  env: { node: '14.0.0', eslint: true, babel: true, typescript: false }
}));

Result:

{
  "name": "Dmitriy",
  "surname": "Pushkov",
  "skills": [
    "JavaScript",
    "Node.js",
    "ES6"
  ],
  "env": {
    "node": "14.0.0",
    "eslint": true,
    "babel": true,
    "typescript": false
  }
}

Incompact object array items

Use compact option:

const perfectJson = require('perfect-json');
console.log(perfectJson([{
  name: 'Dmitriy',
  surname: 'Pushkov'
}, {
  name: 'Tamara',
  surname: 'Pushkova'
}], {
  compact: false
}));

Result:

[
  {
    "name": "Dmitriy",
    "surname": "Pushkov"
  },
  {
    "name": "Tamara",
    "surname": "Pushkova"
  }
]

Set indentation size

Use indent option:

const perfectJson = require('perfect-json');
console.log(perfectJson({
  name: 'Dmitriy',
  surname: 'Pushkov',
  skills: ['JavaScript', 'Node.js', 'ES6'],
  env: { node: '14.0.0', eslint: true, babel: true, typescript: false }
}, {
  indent: 4
}));

Result:

{
    "name": "Dmitriy",
    "surname": "Pushkov",
    "skills": [
        "JavaScript",
        "Node.js",
        "ES6"
    ],
    "env": {
        "node": "14.0.0",
        "eslint": true,
        "babel": true,
        "typescript": false
    }
}

Place specific props on a single line

Use singleLine option:

const perfectJson = require('perfect-json');
console.log(perfectJson({
  name: 'Dmitriy',
  surname: 'Pushkov',
  skills: ['JavaScript', 'Node.js', 'ES6'],
  env: { node: '14.0.0', eslint: true, babel: true, typescript: false }
}, {
  singleLine: ({ key }) => {
    return ['skills', 'env'].includes(key);
  }
}));

Result:

{
  "name": "Dmitriy",
  "surname": "Pushkov",
  "skills": ["JavaScript", "Node.js", "ES6"],
  "env": { "node": "14.0.0", "eslint": true, "babel": true, "typescript": false }
}

Limit single line length

Use maxLineLength option:

const perfectJson = require('perfect-json');
const obj = {
  name: 'Dmitriy',
  surname: 'Pushkov',
  skills: ['JavaScript', 'Node.js', 'ES6'],
  env: { node: "14.0.0", eslint: true, babel: true, typescript: false }
};
console.log(perfectJson(obj, {
  maxLineLength: 40
}));
console.log(perfectJson(obj, {
  maxLineLength: 80
}));

Result:

{
  "name": "Dmitriy",
  "surname": "Pushkov",
  "skills": ["JavaScript", "Node.js", "ES6"],
  "env": {
    "node": "14.0.0",
    "eslint": true,
    "babel": true,
    "typescript": false
  }
}
{
  "name": "Dmitriy",
  "surname": "Pushkov",
  "skills": ["JavaScript", "Node.js", "ES6"],
  "env": { "node": "14.0.0", "eslint": true, "babel": true, "typescript": false }
}

Splitting

Use split and splitResult options together:

const perfectJson = require('perfect-json');
console.log(perfectJson({
  name: 'Dmitriy',
  surname: 'Pushkov',
  skills: ['JavaScript', 'Node.js', 'ES6'],
  env: { node: '14.0.0', eslint: true, babel: true, typescript: false }
}, {
  split: ({ key, depth }) => {
    if (depth !== 1) {
      return null;
    }
    switch (key) {
      case 'skills': return '#skills';
      case 'env': return '#env';
      default: return null;
    }
  },
  splitResult: splitted => {
    console.log(splitted['#skills']);
    console.log(splitted['#env']);
  }
}));

Result:

[
  "JavaScript",
  "Node.js",
  "ES6"
]
{
  "node": "14.0.0",
  "eslint": true,
  "babel": true,
  "typescript": false
}
{
  "name": "Dmitriy",
  "surname": "Pushkov",
  "skills": "#skills",
  "env": "#env"
}

About

Utility function to beautify JSON string...like JSON.stringify() but better

Resources

License

Stars

Watchers

Forks

Packages

No packages published