Package Exports
- destr
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (destr) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
destr
A faster, secure and convenient alternative for
JSON.parse:
Usage
Node.js
Install using npm or yarn:
npm i destr
# or
yarn add destrImport into your Node.js project:
// CommonJS
const destr = require('destr')
// ESM
import destr from 'destr'Deno
import destr from 'https://cdn.jsdelivr.net/gh/nuxt-contrib/destr/src/index.ts'
console.log(destr('{ "deno": "yay" }'))Why?
⚠️ Before reading cool features, please note that destr is not always faster! When parsing a standard JSON string it is about 3 times slower mainly because of transform to avoid prototype pollution which can lead to serious security issues if not being sanetized.
In the other words, destr is better when input is not always a json string or from untrsuted source like request body.
Fast fallback to input if is not string:
// Uncaught SyntaxError: Unexpected token u in JSON at position 0
JSON.parse()
// undefined
destr()// JSON.parse x 5,363,773 ops/sec ±0.31% (96 runs sampled)
JSON.parse(3.14159265359)
// destr x 660,537,795 ops/sec ±0.06% (86 runs sampled)
destr(3.14159265359)Fast lookup for known string values:
// Uncaught SyntaxError: Unexpected token T in JSON at position 0
JSON.parse('TRUE')
// true
destr('TRUE')// JSON.parse x 10,432,994 ops/sec ±0.23% (94 runs sampled)
JSON.parse('true')
// destr x 652,107,152 ops/sec ±0.11% (94 runs sampled
destr('true')Fallback to original value if parse fails (empty or any plain string):
// Uncaught SyntaxError: Unexpected token s in JSON at position 0
// JSON.parse (try-catch) x 248,749 ops/sec ±1.66% (93 runs sampled)
JSON.parse('salam')
// destr x 32,415,523 ops/sec ±0.57% (94 runs sampled)
destr('salam')Avoid prototype pollution:
const input = '{ "user": { "__proto__": { "isAdmin": true } } }'
// { user: { __proto__: { isAdmin: true } } }
JSON.parse(input)
// { user: {} }
destr(input)Better types:
interface JSON {
parse(text: string, reviver?: (this: any, key: string, value: any) => any): any
}function destr(val: string | any): DestrValueLicense
MIT. Made with 💖