A user-friendly wrapper for JSON.parse().
// ✅ Returns type `JsonValue` which is stricter than `unknown`.
// ✅ Fallback specified value is returned if `input` is not a valid JSON string.
const output = parseJson(input, null);
// ^? const output: JsonValue
if (typeof output === "function") {
output;
// ^? const output: never
}
if (output === undefined) {
output;
// ^? const output: never
}
// ❌ Return with type `any`.
// ❌ Might throw an error if `input` is not a valid JSON string.
const vanillaOutput = JSON.parse(input);
// ^? const vanillaOutput: anypnpm i @crescendolab/parse-jsonimport { parseJson } from "@crescendolab/parse-json";
const input = await loadJson();
const output = parseJson(input);parseJson(input, options);- Type:
any
Specify a fallback value to be returned if it fails to parse input as a JSON string.
const input = "not a valid json string";
// ✅ Get `undefined` instead of throwing an error.
const output = parseJson(input, { fallback: undefined });- Type:
(input: string) => JsonValue
Specify a custom parser function.
For example, you can use json5 for comments in json or parse-json for helpful error messages.
import { parseJson } from "@crescendolab/parse-json";
import json5 from "json5";
const input = `{
// This is a comment
"foo": "bar"
}`;
// ✅ This will not throw an error.
const output = parseJson(input, {
parser: json5.parse,
});You can create a parser with a custom default options where the options are the same as the options argument of parseJson().
import { parseJson } from "@crescendolab/parse-json";
const myParser = parseJson.create(options);
const myParser = parseJson.create({ fallback: undefined });MIT © Crescendo lab