We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 68867eb commit 672d7dcCopy full SHA for 672d7dc
src/string.ts
@@ -81,3 +81,22 @@ export function truncateMiddle(
81
);
82
}
83
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