Recursive JSON Value Type

Define a recursive type for arbitrary JSON, then validate unknown input against it to safely walk nested structures without any.

TypescriptData Integrity

Code

typescriptsnippet
29 lines
export type JsonValue =
  | string
  | number
  | boolean
  | null
  | JsonValue[]
  | { [key: string]: JsonValue };

export function isJson(value: unknown): value is JsonValue {
  if (value === null) return true;
  const type = typeof value;
  if (type === "string" || type === "number" || type === "boolean") return true;
  if (Array.isArray(value)) return value.every(isJson);
  if (type === "object") {
    return Object.values(value as Record<string, unknown>).every(isJson);
  }
  return false;
}

export function getIn(data: JsonValue, path: string[]): JsonValue | undefined {
  let current: JsonValue | undefined = data;
  for (const key of path) {
    if (current === null || typeof current !== "object" || Array.isArray(current)) {
      return undefined;
    }
    current = (current as Record<string, JsonValue>)[key];
  }
  return current;
}

What the code does

The working surface is the functions isJson and getIn — everything else is wiring.

Iteration happens inside for (const key of path) — everything outside it runs once.

Watch out for

  • The guard value === null short-circuits the flow with an early return when its condition holds.

Applying it

Entry signature: export function isJson(value: unknown)

Import isJson from the file and call it — the rest of the code is implementation detail.

Statements that matter

if (type === "string" || type === "number" || type === "boolean") return true;
return Object.values(value as Record<string, unknown>).every(isJson);
if (Array.isArray(value)) return value.every(isJson);

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `isJson`, `getIn` at load time.