Skip to content

Commit bd66288

Browse files
committed
feat: add tryAsJSON()
1 parent 8f8de00 commit bd66288

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/tryAsJSON.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import assert from 'node:assert/strict'
2+
import { describe, test as it } from 'node:test'
3+
import { tryAsJSON } from './tryAsJSON.js'
4+
5+
void describe('tryAsJSON()', () => {
6+
void it('should return parsed JSON object if input is a valid JSON string', () => {
7+
const body = '{"name": "John", "age": 30}'
8+
const expected = { name: 'John', age: 30 }
9+
const result = tryAsJSON(body)
10+
assert.deepEqual(result, expected)
11+
})
12+
13+
void it('should return null if input is not a string', () => {
14+
const body = 123
15+
const result = tryAsJSON(body)
16+
assert.equal(result, null)
17+
})
18+
19+
void it('should return null if input is an invalid JSON string', () => {
20+
const body = '{"name": "John", "age": 30' // Missing closing brace
21+
const result = tryAsJSON(body)
22+
assert.equal(result, null)
23+
})
24+
})

src/tryAsJSON.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export const tryAsJSON = (body: unknown): Record<string, any> | null => {
2+
if (typeof body !== 'string') return null
3+
try {
4+
return JSON.parse(body)
5+
} catch {
6+
return null
7+
}
8+
}

0 commit comments

Comments
 (0)