frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

fp.

Open in hackernews

Show HN: handlejson – Safe JSON parsing without try-catch boilerplate

https://github.com/chintanshah35/handlejson
1•chintanshah35•1w ago

Comments

chintanshah35•1w ago
After years of writing try-catch blocks for every JSON.parse, I built handlejson v1.0.0. It is a zero-dependency, 1.5KB library that eliminates boilerplate while hardening your application against common JSON exploits.

The problem:

  let data
  try {
    data = JSON.parse(str)
  } catch {
    data = null
  }
The solution:

  import { parse } from 'handlejson'
  
  const data = parse(str) // null if invalid, no try-catch needed
  const data = parse(str, { default: {} }) // {} if invalid
Key features:

Hardened Security (Protection against common exploits)

Native JSON.parse is vulnerable to resource exhaustion. handlejson adds:

  maxSize: Blocks memory exhaustion from "JSON bombs."
  maxDepth: Prevents stack overflow from deeply nested objects.
  safeKeys: Automatically blocks prototype pollution (__proto__).

  parse(userInput, {
    maxSize: 10 * 1024 * 1024,
    maxDepth: 100,
    safeKeys: true
  })
High Performance

- Small JSON: 5.2M ops/s - With security checks enabled: 3.4M ops/s - Bundle size: 1.5KB gzipped (Zero dependencies)

Advanced Handling

- Circular References: stringify() handles circular structures automatically.

- Date & BigInt: Automatic serialization and revival without manual revivers.

- Detailed Errors: Precise error position and context instead of "Unexpected token."

- Stream Parsing: Support for parsing large files in chunks.

- Schema Validation: Validate structure without extra dependencies.

- Error Tuples: Get error objects instead of null.

- Validation: Check validity without parsing.

- Format & Minify: Pretty-print or compress JSON.

- Reviver/Replacer: Custom transformation functions (like native JSON).

Reliability:

- 244 tests covering security, streams, and edge cases. - CI/CD tested on Node 18, 20, and 22. - TypeScript-first with full type support.

Blog Post (Deep Dive): https://chintanshah35.hashnode.dev/introducing-handlejson-v1...

GitHub: https://github.com/chintanshah35/handlejson

NPM: https://www.npmjs.com/package/handlejson

More of my work: https://dev.to/chintanshah35