Skip to content

Commit

Permalink
feat: add option strict that throws an error if the input is not va…
Browse files Browse the repository at this point in the history
…lid JSON (#11)
  • Loading branch information
tobiasdiez committed Oct 19, 2022
1 parent 2f66125 commit 36c7121
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
18 changes: 18 additions & 0 deletions README.md
Expand Up @@ -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.
Expand Down
14 changes: 12 additions & 2 deletions src/index.ts
Expand Up @@ -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
}
Expand All @@ -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
}

Expand All @@ -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
}
}

0 comments on commit 36c7121

Please sign in to comment.