UNPKG

wellcrafted

Version:

Delightful TypeScript patterns for elegant, type-safe applications

51 lines (49 loc) 1.65 kB
import { trySync } from "./result-C_ph_izC.js"; import { defineErrors, extractErrorMessage } from "./error-BkeqDeUq.js"; import "./tap-err-BENAkFsH.js"; import "./result-pV2mfn0W.js"; //#region src/json.ts /** * Constructs a {@link JsonParseError}. Returns `Err<JsonParseError>` directly, * ready to return from a `trySync`/`tryAsync` catch handler. */ const { JsonParseError } = defineErrors({ JsonParseError: ({ cause }) => ({ message: `Failed to parse JSON: ${extractErrorMessage(cause)}`, cause }) }); /** * Parses a JSON string into a {@link JsonValue}, returning a `Result` instead * of throwing. * * Unlike `JSON.parse`, which returns `any` and throws on malformed input, this: * - types the success value as {@link JsonValue}, forcing you to narrow or * validate before treating it as a known shape * - reports failure as a tagged {@link JsonParseError} rather than an exception * * No reviver argument is accepted. A reviver can return arbitrary values, which * would make the {@link JsonValue} success type a lie. * * @param text - The JSON string to parse. * @returns `Ok<JsonValue>` on success, `Err<JsonParseError>` on malformed input. * * @example * ```ts * import { parseJson } from "wellcrafted/json"; * * const { data, error } = parseJson('{"count":1}'); * if (error) { * console.error(error.message); // "Failed to parse JSON: ..." * } else { * data; // JsonValue — narrow or validate before using * } * ``` */ function parseJson(text) { return trySync({ try: () => JSON.parse(text), catch: (cause) => JsonParseError({ cause }) }); } //#endregion export { JsonParseError, parseJson }; //# sourceMappingURL=json.js.map