Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 13x 7x 1x 6x 6x 5x 1x | /**
* @module
*
* @author Bayu Dwiyan Satria
* @version 1.0.0
* @since 1.3.0
*/
/**
* @class
*
* Parses untrusted JSON without throwing on invalid syntax.
*
* @remarks
* Parsing does not validate the result's shape. Callers must check the fields
* they need, even when they supply a type argument.
*
* @example
* ```ts
* const input = Json.parse<{ symbol?: string }>(await request.text())
*
* if (!input) {
* return fail('Body must be valid JSON')
* }
* ```
*
* @author Bayu Dwiyan Satria
* @version 1.0.0
* @since 1.3.0
*/
export class Json {
/**
* Parses JSON, returning null for empty input, invalid syntax, or a null literal.
*
* @typeParam T The expected shape, which is not validated.
* @param text The raw text to parse.
* @returns The parsed value, including valid primitives, or null.
*/
public static parse<T = unknown>(text: string): T | null {
if (!text) {
return null
}
try {
const value = JSON.parse(text)
return value === null ? null : (value as T)
} catch {
return null
}
}
}
|