destr
A faster, secure and convenient alternative for JSON.parse
.
Usage
Node.js
Install dependency:
npm i destr
yarn add destr
pnpm i destr
Import into your Node.js project:
import { destr, safeDestr } from "destr";
const { destr, safeDestr } = require("destr");
Deno
import { destr, safeDestr } from "https://deno.land/x/destr/src/index.ts";
console.log(destr('{ "deno": "yay" }'));
Why?
✅ Type Safe
const obj = JSON.parse("{}");
const obj = destr("{}");
const obj = destr<MyInterface>("{}");
✅ Fast fallback to input if is not string
JSON.parse();
destr();
✅ Fast lookup for known string values
JSON.parse("TRUE");
destr("TRUE");
✅ Fallback to original value if parse fails (empty or any plain string)
JSON.parse("salam");
destr("salam");
Note: This fails in safe/strict mode with safeDestr
.
✅ Avoid prototype pollution
const input = '{ "user": { "__proto__": { "isAdmin": true } } }';
JSON.parse(input);
destr(input);
✅ Strict Mode
When using safeDestr
it will throw an error if the input is not a valid JSON string or parsing fails. (non string values and built-ins will be still returned as-is)
destr("[foo");
safeDestr("[foo");
Benchmarks
destr
is faster generally for arbitrary inputs but also sometimes little bit slower than JSON.parse
when parsing a valid JSON string mainly because of transform to avoid prototype pollution which can lead to serious security issues if not being sanitized. In the other words, destr
is better when input is not always a JSON string or from untrusted source like request body.
Check Benchmark Results or run with pnpm run bench:node
or pnpm run bench:bun
yourself!
License
MIT. Made with 💖