You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constobj=JSON.parse("{}");// obj type is anyconstobj=destr("{}");// obj type is unknown by defaultconstobj=destr<MyInterface>("{}");// obj is well-typed
✅ Fast fallback to input if is not string
// Uncaught SyntaxError: Unexpected token u in JSON at position 0JSON.parse();// undefineddestr();
✅ Fast lookup for known string values
// Uncaught SyntaxError: Unexpected token T in JSON at position 0JSON.parse("TRUE");// truedestr("TRUE");
✅ Fallback to original value if parse fails (empty or any plain string)
// Uncaught SyntaxError: Unexpected token s in JSON at position 0JSON.parse("salam");// "salam"destr("salam");
Note: This fails in safe/strict mode with safeDestr.
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)
// Returns "[foo"destr("[foo");// Throws an errorsafeDestr("[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 💖
About
🚀 Faster, secure and convenient alternative for JSON.parse for arbitrary inputs