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.
  • 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.

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

Anthropic Launches Projects Feature for Claude Cowork Desktop

Anthropic is expanding Claude Cowork Desktop with a new Projects feature designed to keep files,…

1 hour ago

Ossian Woman Sentenced To Five Years

FORT WAYNE, Ind. (AP) —  A 63 year old Ossian woman has been sentenced to…

1 hour ago

Crimson Desert Players Think They’ve Found AI-Generated Art In-Game

Crimson Desert just launched yesterday to a bit of a chaotic and mixed reception from…

2 hours ago

The FlashForge AD5X Is One of the Best Multi-Color 3D Printers Priced Below $300

One of the better regarded 3D printers with multi-color print capability is now priced well…

2 hours ago

Today’s Top Deals: Sonic Mini Arcade Cabinet, Budget ASUS TUF Gaming Monitor, and Crimson Desert for PC

Spring is officially here, and that means we’re in for tons of spring sales events…

2 hours ago

This website uses cookies.