VOOZH about

URL: https://dev.to/yairlenga/making-pretty-printed-json-readable-again-in-javascript-3g3n

⇱ Making Pretty-Printed JSON Readable Again in JavaScript - DEV Community


Most JSON serializers give you only two choices:

  • compact machine output:
{"a":{"b":{"c":"abc"}},"x":{"y":{"z":"xyz"}}}
  • or fully expanded β€œpretty-print”:
{"a":{"b":{"c":"abc"}},"x":{"y":{"z":"xyz"}}}

I wanted something in between: the first is hard for humans to scan, and the second becomes extremely verbose on real-world nested data.

The Idea

I wrote a small JavaScript module called jsonfold. Instead of replacing JavaScript's JSON serializer, it works as a lightweight post-processing filter on top of JSON.stringify() output.

The formatter selectively:

  • folds small containers back onto one line,
  • packs short scalar sequences,
  • keeps large or complex structures expanded.

Example output:

{"a":{"b":{"c":"abc"}},"x":{"y":{"z":"xyz"}}}

Why This Approach?

I did not want to rebuild a serializer. JavaScript already provides an excellent serializer in JSON.stringify(), including support for custom transformations through the replacer callback and configurable indentation.

The formatter can be used either as a streaming filter or through convenience wrappers that behave similarly to JSON.stringify().

import { stringify } from "@jsonfold/core";

const data = {
 a: { b: { c: "abc" } },
 x: { y: { z: "xyz" } }
};

console.log(stringify(data));

That means you can continue using the standard JavaScript serialization pipeline while producing more compact and readable output.

Customization

The formatter allows controlling:

  • maximum line width,
  • folding depth,
  • packing aggressiveness,
  • array/object limits.

So you can choose between conservative formatting and more aggressive compaction.

Full Article:

Medium (no paywall): A Streaming JSON Formatter for JavaScript that Works with JSON.stringify

Minimal Usage

Install:

npm install @jsonfold/core
import { dump } from "@jsonfold/core";

const data = {
 meta: { version: 1, ok: true },
 ids: [1, 2, 3, 4, 5],
 items: [
 { id: 1, name: "alpha" },
 { id: 2, name: "beta" }
 ]
};

// compact can be: default, low, med, high, max
dump(data, process.stdout, {
 compact: "default"
});

GitHub Project

Web site: https://jsonfold.dev/

Repository: https://github.com/yairlenga/jsonfold

JavaScript implementation is under the javascript directory.

Future articles will cover other implementations: Python, Java, Perl, C, ... please watch the GitHub project, or follow the articles on Medium.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.