Parse Any JSON
Parse any JSON string into a structured value, with optional deep parsing of stringified primitives.
parseJSON
Parses any valid JSON string (including arrays, primitives, or objects) and optionally converts stringified primitives in nested arrays or objects. This utility is ideal when the root value of the JSON could be anything, not just an object.
Example Usage
playground.ts
Function Signature
function parseJSON<T = unknown>(value: string, parsePrimitives?: boolean): TParameters
| Parameter | Type | Description |
|---|---|---|
value | string | The JSON string to parse. |
parsePrimitives | boolean (optional) | If true (default), recursively converts stringified primitives. |
Returns
T: The parsed JSON value (typed asT), which may be an object, array, string, number, or boolean. Returns{}if the input is not valid JSON.
Key Features
- Flexible Root: Accepts any valid JSON root (object, array, primitive).
- Recursive Primitive Conversion: Converts stringified numbers, booleans,
null—deeply (see deepParsePrimitives). - Safe Fallback: Malformed or invalid JSON always returns an empty object.
- Type-safe Generic: Infer and enforce types with
<T>.
Aliases
Also exported as:
parseJsonDeep
Limitations
- Invalid input returns
{}: May mask input errors—double-check your sources. - Only JSON-safe types: Non-JSON, circular, or function values will not parse.
- No Reviver Support: Doesn't expose a custom reviver function like
JSON.parse. - Single Quoted Strings Not Supported: Must be valid JSON (double quotes).
Notes
- For strict object parsing (root must be an object), use
parseJsonToObject. - For deep primitive conversion logic, see
deepParsePrimitives. - Malformed JSON, such as single-quoted or badly formatted strings, will not throw but will result in
{}.
Recommended Use Cases
- Parsing unpredictable API or config data.
- Accepting JSON from user input, file uploads, or dynamic sources.
- Applications handling both primitive and complex JSON shapes.
Last updated: Sun, Jun 14, 2026 07:06:16AM (UTC)
