// 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);
}

// denoCacheMetadata={"headers":{"etag":"\"645b8907f92e522c64d25bea05501d05\"","vary":"Origin","content-length":"942","cache-control":"public, max-age=31536000, immutable","accept-ranges":"bytes","set-cookie":"__cf_bm=r.2dkqjgHNRGwyJHB7euNHrRXuYEsHrrvkTiB.zoC.8-1785241875.1902602-1.0.1.1-RUhNtDjkrxq_8_UHNLRuvwsiMwTTTxUX.w4t1Oa70BWnoy_Sw8r893miJFiCb2WvdVbQV2sLnX1inWC4CfGlsV1Uy9snYQlCwJBLJKz0Ill9WVpAMzC4H9LW_NpukqlC; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","date":"Tue, 28 Jul 2026 12:31:15 GMT","cross-origin-resource-policy":"cross-origin","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=eYFvLNzW3gbO%2BO9MNeQ4KLhSsp0rMADwSiZWdMH15sOcgSYMIEoPUQnbDOd8KiB4ITHTIOW%2FV3Pl%2F1Mfuty8G18FaFu0F1UJIon%2FSnEMBkHRIReO3S6GSbo%3D\"}]}","x-jsr-backend":"modules","x-robots-tag":"noindex","server":"cloudflare","content-type":"text/typescript","cf-ray":"a223e657eae77db6-LAX","cf-cache-status":"HIT","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","access-control-expose-headers":"*","x-content-type-options":"nosniff","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","access-control-allow-origin":"*","alt-svc":"h3=\":443\"; ma=86400","age":"112265"},"url":"https://jsr.io/@std/streams/0.224.5/to_json.ts","time":1785241875}