Skip to content

Commit 672d7dc

Browse files
committed
feat(string): add safe parse util
1 parent 68867eb commit 672d7dc

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/string.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,22 @@ export function truncateMiddle(
8181
);
8282
}
8383
}
84+
85+
/**
86+
* Safely parses a JSON string, returning `undefined` if parsing fails.
87+
*
88+
* ```ts
89+
* safeParse<{ a: number }>('{"a": 1}'); // { a: 1 }
90+
* safeParse<{ a: number }>('invalid json'); // undefined
91+
* safeParse<{ a: number }>(null); // undefined
92+
* ```
93+
*/
94+
export function safeParse<T>(jsonString: Maybe<string>): T | undefined {
95+
if (typeof jsonString !== 'string') return undefined;
96+
97+
try {
98+
return JSON.parse(jsonString) as T;
99+
} catch {
100+
return undefined;
101+
}
102+
}

0 commit comments

Comments
 (0)