Parse Any JSON (Flexible Root)
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.
Import
import { parseJSON } from 'nhb-toolbox';
import { parseJsonDeep } from 'nhb-toolbox';
Function Signature
function parseJSON<T = unknown>(
value: string,
parsePrimitives?: boolean
): T
Usage Examples
- Root Object
- Root Array
- Primitive Root
- No Primitive Conversion
- Malformed Input
parseJSON('{ "a": "1", "b": 2 }');
// Returns: { a: 1, b: 2 }
parseJSON('[ "1", "2", 3 ]');
// Returns: [1, 2, 3]
parseJSON('"42"');
// Returns: 42
parseJSON('{"x":"false"}', false);
// Returns: { x: "false" }
parseJSON("{ key: 'value' }");
// Returns: {}
API Reference
Parameters
Name | Type | Description |
---|---|---|
value | string | The JSON string to parse. |
parsePrimitives | boolean | Optional. If true (default), recursively converts stringified primitives. |
Returns
- The parsed JSON value (typed as
T
), 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.
See Also
deepParsePrimitives
: Recursively converts stringified primitives inside objects/arrays.parseJsonToObject
: LikeparseJSON
, but root must be an object.JSON.parse
(MDN): Built-in JSON parsing in JS.
Conclusion:
parseJSON
provides a robust, type-safe, and deep-parsing JSON parser for any root shape. Prefer it when input is not always an object—or for extra primitive safety!