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

snippet
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;
}