Categories: CSSScriptWeb Design

Lossless JSON Pretty-Printer for JavaScript – fast-json-format

fast-json-format is a super tiny JavaScript library that pretty-prints JSON strings without losing data or breaking on minor syntax issues.

Unlike the standard JSON.stringify(JSON.parse(str)) method, it avoids altering the source data, preserving numeric precision and handling BigInts correctly.

It also gracefully formats imperfect or malformed JSON without throwing errors.

Features:

  • Forgiving Parser: Handles malformed or imperfect JSON without crashing.
  • Data Preservation: Retains BigInt literals and numeric precision, such as trailing zeroes in decimals.
  • Sponsored
  • Custom Indentation: Supports custom strings for indentation.
  • Performance: Operates by scanning the string rather than full parsing.

Use Cases:

  • JSON Viewers and Editors: When building a tool to display API responses, you can format the JSON for readability without worrying that the tool will crash on a syntax error or misrepresent a large ID number.
  • Logging and Debugging: For logging JSON payloads, fast-json-format ensures that what you see in the logs is an exact, readable representation of the data that was transmitted, with no precision loss on large numbers.
  • Configuration File Formatters: If you’re creating a CLI that tidies up user-edited configuration files, this library can apply consistent formatting without being overly strict about syntax.
  • Data Transformation Pipelines: In scenarios where you only need to reformat a JSON string before passing it to another service, this library avoids the performance overhead of a full parse-and-stringify operation.

How To Use It:

1. Install fast-json-format through npm:

# NPM
$ npm install fast-json-format

2. Import the library and pass a JSON string to format:

const fastJsonFormat = require('fast-json-format');
const minified = '{"person":{"name":"Alice","details":{"age":25,"address":{"street":"123 Main St","city":"Boston","country":"USA"}},"hobbies":["reading","coding","travel"]}}';
const formatted = fastJsonFormat(minified);
console.log(formatted);
// Output
{
  "users": [
    {
      "id": 1,
      "name": "John",
      "email": "john@example.com",
      "active": true
    },
    {
      "id": 2,
      "name": "Jane",
      "email": "jane@example.com",
      "active": false
    },
    {
      "id": 3,
      "name": "Bob",
      "email": "bob@example.com",
      "active": true
    }
  ],
  "total": 3
}

3. The second parameter controls indentation spacing. Pass any string to define custom indent levels:

// Four spaces per level
const formatted = fastJsonFormat(jsonString, '    ');

// Tab indentation
const formatted = fastJsonFormat(jsonString, 't');

// Minified output (no indentation)
const formatted = fastJsonFormat(jsonString, '');

How It Works

fast-json-format works by being a string scanner, not a true parser. Instead of converting the JSON string into a JavaScript object and back again, it iterates through the string one character at a time.

The core mechanism scans for structural characters like {, }, [, ], ,, and :. When it encounters a " it scans the entire string literal, respecting escape sequences but without validating the content. Everything else—numbers, true, false, null, and even malformed values—is treated as an “atom” and copied directly to the output.

Sponsored

This design is intentionally forgiving. An unterminated string or a missing comma won’t cause an error; the scanner will simply copy the content as it sees it. For performance, the function builds an array of string chunks and joins them at the end, which is significantly faster than concatenating strings in a loop.

FAQs:

Q: Why is fast-json-format slower than the native JSON.stringify?
A: JSON.stringify is implemented in C++ within the JavaScript engine, making it exceptionally fast. fast-json-format is a JavaScript-based scanner. Its purpose isn’t to outperform the native function in speed but to provide safe, non-lossy formatting that the native method cannot guarantee.

Q: How does it handle comments in a JSONC file?
A: It doesn’t officially support comments. Because it treats anything that isn’t a string or structural token as an “atom,” it will likely print the comment content but may mess up the indentation around it. It’s built for JSON-like strings, so its behavior on formats like JSONC isn’t guaranteed.

Q: Can I use this library to validate JSON?
A: No, it’s not a validator. In fact, its design philosophy is the opposite. It’s meant to be forgiving of syntax errors. If you need to ensure JSON is valid, you should use a dedicated schema validation library.

Q: How can I use fast-json-format in a browser without a build step?
A: The library is a single JavaScript file with no dependencies. You can easily adapt the module.exports line to assign the fastJsonFormat function to the global window object, allowing you to include it with a simple <script> tag.

Related Resources:

The post Lossless JSON Pretty-Printer for JavaScript – fast-json-format appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Bruce Lee Day in California? A New Bill Is Fighting to Make It Happen

A new bill may see May 17 become Bruce Lee Day in California, thanks to…

2 minutes ago

Behind The Rubberhose Curtain of MOUSE: P.I. For Hire – IGN First

As our exclusive, all-February-long IGN First "cover story" on the upcoming black-and-white, hand-animated first-person shooter…

2 minutes ago

Scream 7 Review

“Burn it all down.” For a tagline so front and center of Paramount’s marketing for…

2 minutes ago

Check Out Some of the Great Games on Sale at Woot for $20 or Less

Video game deals have been popping up all over the place lately. Alongside PlayStation’s big…

2 minutes ago

Your smart TV may be crawling the web for AI

This is Lowpass by Janko Roettgers, a newsletter on the ever-evolving intersection of tech and…

37 minutes ago

This website uses cookies.