diff --git a/README.md b/README.md index 580f8c1..6b89a53 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,24 @@ import destr from 'https://deno.land/x/destr/src/index.ts' console.log(destr('{ "deno": "yay" }')) ``` +### Options + +`destr` allows the following options as the second argument: + +#### `strict` + +Default: `false` + +If set to `true`, `destr` will throw an error if the input is not a valid JSON string or parsing fails. + +```js +// Returns "[foo" +destr('[foo') + +// Throws an error +destr('[foo', { strict: true }) +``` + ## Why? Please note that `destr` is little bit slower when parsing a standard JSON string mainly because of transform to avoid [prototype pollution](https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061) 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. diff --git a/src/index.ts b/src/index.ts index 5c2bfd9..4135519 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,7 +12,11 @@ function jsonParseTransform (key: string, value: any): any { return value } -export default function destr (val: any): any { +export type Options = { + strict?: boolean +} + +export default function destr (val: any, options: Options = {}): any { if (typeof val !== 'string') { return val } @@ -26,6 +30,9 @@ export default function destr (val: any): any { if (_lval === 'undefined') { return undefined } if (!JsonSigRx.test(val)) { + if (options.strict) { + throw new SyntaxError('Invalid JSON') + } return val } @@ -34,7 +41,10 @@ export default function destr (val: any): any { return JSON.parse(val, jsonParseTransform) } return JSON.parse(val) - } catch (_e) { + } catch (error) { + if (options.strict) { + throw error + } return val } }