Function toJson

  • Converts a https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON-formatted ReadableSteam of strings or Uint8Arrays to an object. Works the same as Response.json and Request.json, but also extends to support streams of strings.

    Parameters

    • stream: ReadableStream<Uint8Array> | ReadableStream<string>

      A ReadableStream whose chunks compose a JSON.

    Returns Promise<unknown>

    A promise that resolves to the parsed JSON.

    import { toJson } from "@std/streams/to-json";
    import { assertEquals } from "@std/assert";

    const stream = ReadableStream.from([
    "[1, true",
    ', [], {}, "hello',
    '", null]',
    ]);
    assertEquals(await toJson(stream), [1, true, [], {}, "hello", null]);
    import { toJson } from "@std/streams/to-json";
    import { assertEquals } from "@std/assert";

    const stream = ReadableStream.from([
    "[1, true",
    ', [], {}, "hello',
    '", null]',
    ]).pipeThrough(new TextEncoderStream());
    assertEquals(await toJson(stream), [1, true, [], {}, "hello", null]);