toJson

tcmts.cli.data_pages.toJson · #3pjfldp6 · term · runs anywhere

A row's value as JSON, to read and edit: dates as ISO strings, maps as [key, value] pairs, sets and arrays as arrays, bigints as their digits; fromJson brings it back by the table's row type.

export function toJson(v: unknown): unknown {
  if (v instanceof Date) return v.toISOString();
  if (v instanceof Map) return [...v].map(([k, x]) => [toJson(k), toJson(x)]);
  if (v instanceof Set) return [...v].map(toJson);
  if (typeof v === "bigint") return v.toString();
  if (Array.isArray(v)) return v.map(toJson);
  if (v && typeof v === "object")
    return Object.fromEntries(
      Object.entries(v)
        .filter(([, x]) => x !== undefined)
        .map(([k, x]) => [k, toJson(x)]),
    );
  return v;
}

used by