ts-data-forge
    Preparing search index...

    Function parse

    • Safely converts a JSON string into a JavaScript value without throwing exceptions.

      This function provides type-safe JSON parsing by wrapping the native JSON.parse in a Result type, allowing you to handle parsing errors gracefully without try-catch blocks.

      Parameters

      • text: string

        A valid JSON string to parse. Can contain any valid JSON data type: primitives (string, number, boolean, null), arrays, or objects.

      • Optionalreviver: (this: unknown, key: string, value: JsonValue) => unknown

        Optional function that transforms parsed values. Called for each key-value pair in the JSON. The function receives the key name and parsed value, and should return the transformed value. For nested objects, inner objects are processed before outer objects.

      Returns Result<JsonValue, string>

      A Result<JsonValue, string> containing:

      • On success: Result.ok(parsedValue) where parsedValue is the parsed JSON
      • On failure: Result.err(errorMessage) where errorMessage describes the parsing error
      const validJson = '{"name": "Alice", "age": 30}';
      const invalidJson = '{invalid json}';

      const parsed = Json.parse(validJson);
      const failed = Json.parse(invalidJson);

      assert.ok(Result.isOk(parsed));
      if (Result.isOk(parsed)) {
      assert.deepStrictEqual(parsed.value, { name: 'Alice', age: 30 });
      }

      assert.ok(Result.isErr(failed));

      // With reviver
      const jsonWithDate = '{"created": "2024-01-01T00:00:00.000Z"}';
      const withReviver = Json.parse(jsonWithDate, (key, value) => {
      if (key === 'created' && typeof value === 'string') {
      return new Date(value);
      }
      return value;
      });

      assert.ok(Result.isOk(withReviver));