std/streams/to_json.ts
Yusuke Tanaka 9c3c53e65b
docs(streams): improve docs for stabilization (#4852)
This commit improves docs of the streams module.

Towards #3764

---------

Co-authored-by: Yoshiya Hinosawa <stibium121@gmail.com>
2024-05-27 18:27:40 -07:00

33 lines
942 B
TypeScript

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
import { toText } from "./to_text.ts";
/**
* Converts a JSON-formatted {@linkcode ReadableSteam} of strings or
* {@linkcode Uint8Array}s to an object. Works the same as
* {@linkcode Response.json}.
*
* @param readableStream A `ReadableStream` whose chunks compose a JSON.
* @returns A promise that resolves to the parsed JSON.
*
* @example Basic usage
* ```ts
* import { toJson } from "@std/streams/to-json";
* import { assertEquals } from "@std/assert/assert-equals";
*
* const stream = ReadableStream.from([
* "[1, true",
* ', [], {}, "hello',
* '", null]',
* ]);
* const json = await toJson(stream);
* assertEquals(json, [1, true, [], {}, "hello", null]);
* ```
*/
export function toJson(
readableStream: ReadableStream,
): Promise<unknown> {
return toText(readableStream).then(JSON.parse);
}