10LOC

#json

TypeScriptintermediate

A recursive type for JSON-safe values

type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };

const isJsonValue = (value: unknown): value is JsonValue => {
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
  if (Array.isArray(value)) return value.every(isJsonValue);

Define exactly what JSON.stringify can round-trip, recursively, and use it to reject values like undefined, functions, and Dates.

Node.jsadvanced

Streaming a large JSON array without loading it into memory

import type { Writable } from "node:stream";

export const streamJsonArray = async (rows: AsyncIterable<unknown>, out: Writable) => {
  out.write("[");
  let first = true;

Write a large JSON array to a stream item by item as it's produced, instead of building the whole array in memory before calling JSON.stringify.