Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add option strict that throws an error if the input is not valid JSON #11

Merged
merged 3 commits into from
Oct 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
}
}