Recursive JSON Value Type
Define a recursive type for arbitrary JSON, then validate unknown input against it to safely walk nested structures without any.
Code
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 === nullshort-circuits the flow with an earlyreturnwhen 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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.