@kaelyx/ts-kit / string / parseJson
Function: parseJson()
parseJson<
T>(input):Result<T,SyntaxError>
Defined in: string/parse-json/parse-json.ts:24
Parses a JSON string and returns a result indicating success or failure.
Type Parameters
T
T = unknown
Parameters
input
string
The JSON string to parse. An empty string will result in a failure.
Returns
Result<T, SyntaxError>
A result object indicating success or failure. On success, the value property contains the parsed object. On failure, the error property contains the SyntaxError.
Throws
If the input is not a valid JSON string and the error is not a SyntaxError, the function will rethrow the error.
Example
ts
parseJson('{"key": "value"}') // { ok: true, value: { key: 'value' } }
parseJson('invalid json') // { ok: false, error: SyntaxError }
parseJson('[1, 2, 3]') // { ok: true, value: [1, 2, 3] }
parseJson('null') // { ok: true, value: null }
parseJson('') // { ok: false, error: SyntaxError }