Function json

  • The json function is a parsing utility to get a typed and runtime-validated object out of a JSON string. It exists in two versions: one that returns a Result and one that throws an error if the validation fails.

    Safe version

    Example

    import { json } from "typerun";
    import { object, string } from "typerun/schema";
    import { isOk } from "typerun/result";

    const schema = object({ name: string });
    const result = json(schema)(`{"name": "Alice"}`);
    if (isOk(result)) {
    console.log(result.data.name); // "Alice"
    }

    Type Parameters

    • S

    Parameters

    • schema: Schema<S>

      The schema to validate the parsed JSON against.

    • Optional options: {
          throwing?: false;
      }

      Options to control the behavior of the validation.

      • Optional throwing?: false

    Returns ((toParse) => Result<S, ParseError>)

    A function that takes a JSON string and returns a Result with the parsed object or a list of errors.

  • Throwing version

    Example

    import { json } from "typerun";
    import { object, string } from "typerun/schema";
    import { isOk } from "typerun/result";

    const schema = object({ name: string });
    try {
    const result = json(schema, { throwing: true })(`{"name": "Alice"}`);
    console.log(result.name); // "Alice"
    } catch (errors) {
    console.error(errors);
    }

    Type Parameters

    • S

    Parameters

    • schema: Schema<S>

      The schema to validate the parsed JSON against.

    • options: {
          throwing: true;
      }

      Options to control the behavior of the validation.

      • throwing: true

    Returns ((toParse) => S)

    A function that takes a JSON string and returns the parsed object or throws an array of errors if the validation fails.

      • (toParse): S
      • Parameters

        • toParse: string

        Returns S