JSON viewer
An expandable JSON tree with key and value search, native page disclosures and copying for the selected value or path.
pnpm dlx shadcn@latest add @haze/json-viewer---
import { Braces, ChevronRight } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import SearchField from "./search-field.astro";
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
interface Props {
id: string;
data: Json;
label?: string;
rootName?: string;
openDepth?: number;
pageSize?: number;
class?: string;
}
const { id, data, label = "JSON payload", rootName = "payload", openDepth = 1, pageSize = 40, class: className } = Astro.props;
const pageLength = Number.isFinite(pageSize) ? Math.max(1, Math.floor(pageSize)) : 40;
let source: string | undefined;
try { source = JSON.stringify(data); } catch { /* A cyclic or non-JSON input has no serializable value. */ }
const value: Json | undefined = source === undefined ? undefined : JSON.parse(source);
const rowClass = "flex min-h-8 min-w-0 flex-wrap items-baseline gap-x-1.5 rounded-xs px-2 py-1 font-mono text-[0.8125rem]/5 wrap-anywhere text-start focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring data-[current]:bg-muted data-[match]:underline data-[match]:decoration-brand data-[match]:underline-offset-4";
---
<div data-haze-json-viewer class={cn("grid min-w-0 gap-3 rounded-xl border border-border bg-card p-3 sm:p-4.5", className)}>
<div class="flex min-w-0 items-center gap-2 text-[0.8125rem]/5 font-medium">
<Braces class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" /><span id={`${id}-label`} class="wrap-anywhere">{label}</span>
</div>
{value !== undefined ? (
<>
<template data-json-source>{source}</template>
<div data-json-tools hidden class="grid min-w-0 gap-1 [&[hidden]]:hidden">
<SearchField id={`${id}-search`} label="Search keys and values" placeholder="Find in JSON" hideLabel autocomplete="off" />
<span data-json-count role="status" aria-atomic="true" class="text-xs/5 text-muted-foreground empty:sr-only"></span>
</div>
<div data-json-scroll role="region" aria-labelledby={`${id}-label`} tabindex="0" class="max-h-96 min-w-0 overflow-y-auto rounded-lg border border-border bg-background p-1.5 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring">
{(() => {
const renderNode = (key: string, item: Json, depth: number): astroHTML.JSX.Element => {
const array = Array.isArray(item);
const container = item !== null && typeof item === "object";
const children: [string, Json][] = container ? Object.entries(item) : [];
const name = /^[A-Za-z_$][\w$]*$|^\d+$/.test(key) ? key : JSON.stringify(key);
const singular = array ? "item" : "key";
const count = children.length + " " + singular + (children.length === 1 ? "" : "s");
if (!children.length) {
const text = JSON.stringify(item);
return (
<div data-json-node data-key={JSON.stringify(key)}>
<span data-json-row tabindex="-1" class={rowClass}>
<span class="text-muted-foreground">{name}<span aria-hidden="true">:</span></span>
<span data-json-scalar class={cn("min-w-0 whitespace-break-spaces", "text-foreground tabular-nums")}>{text}</span>
</span>
</div>
);
}
const renderChildren = (start: number) => children.slice(start, start + pageLength).map(([name, child]) => renderNode(name, child, depth + 1));
return (
<details data-json-node data-key={JSON.stringify(key)} open={depth < openDepth}
class="min-w-0 [&[open]>summary>svg]:rotate-90">
<summary data-json-row class={cn(rowClass, "cursor-pointer list-none hover:bg-accent [&::-webkit-details-marker]:hidden")}>
<ChevronRight aria-hidden="true" class="size-3 shrink-0 self-center text-muted-foreground transition-[rotate] duration-200 ease-spring motion-reduce:transition-none" />
<span class="font-semibold">{name}</span><span class="text-muted-foreground">{array ? "[ ]" : "{ }"} · {count}</span>
</summary>
<div class={cn("min-w-0", depth < 6 && "ms-1.5 border-s border-border ps-1.5 sm:ms-2 sm:ps-2")}>
{renderChildren(0)}
{Array.from({ length: Math.ceil(children.length / pageLength) - 1 }, (_, page) => {
const start = (page + 1) * pageLength;
const end = Math.min(start + pageLength, children.length);
const range = start + 1 === end ? (array ? "Item " : "Key ") + end : (array ? "Items " : "Keys ") + (start + 1) + "–" + end;
return (
<details class="min-w-0 [&[open]>summary>svg]:rotate-90">
<summary data-json-page class={cn(rowClass, "cursor-pointer list-none text-muted-foreground hover:bg-accent [&::-webkit-details-marker]:hidden")}>
<ChevronRight aria-hidden="true" class="size-3 shrink-0 self-center transition-[rotate] duration-200 ease-spring motion-reduce:transition-none" />
{range}
</summary>
{renderChildren(start)}
</details>
);
})}
</div>
</details>
);
};
return renderNode(rootName, value, 0);
})()}
</div>
<div data-json-tools hidden class="grid min-w-0 gap-2 [&[hidden]]:hidden">
<code data-json-path class="font-mono text-xs/5 wrap-anywhere text-muted-foreground">{rootName}</code>
<div class="flex min-w-0 flex-wrap gap-2">
<Button data-copy-kind="value" size="sm" variant="outline">Copy value</Button>
<Button data-copy-kind="path" size="sm" variant="ghost">Copy path</Button>
</div>
<span data-copy-result role="status" aria-atomic="true" class="text-xs/5 text-muted-foreground empty:sr-only"></span>
<textarea data-copy-fallback hidden readonly aria-label="Text to copy manually" class="w-full rounded-lg border border-frame-input bg-field p-2 font-mono text-xs/5 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden [&[hidden]]:hidden"></textarea>
</div>
</>
) : <p class="text-sm/5 text-muted-foreground">This value cannot be represented as JSON.</p>}
</div>
<script>
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const source = root.querySelector<HTMLTemplateElement>("[data-json-source]");
const scroll = root.querySelector<HTMLElement>("[data-json-scroll]");
const search = root.querySelector<HTMLInputElement>("input[type=search]");
const pathLabel = root.querySelector<HTMLElement>("[data-json-path]");
const count = root.querySelector<HTMLElement>("[data-json-count]");
const result = root.querySelector<HTMLElement>("[data-copy-result]");
const fallback = root.querySelector<HTMLTextAreaElement>("[data-copy-fallback]");
if (!source || !scroll || !search || !pathLabel || !count || !result || !fallback) return;
const payload: Json = JSON.parse(source.content.textContent!);
const nodes = Array.from(scroll.querySelectorAll<HTMLElement>("[data-json-node]"));
const rows = Array.from(scroll.querySelectorAll<HTMLElement>("[data-json-row], [data-json-page]"));
const allBranches = Array.from(scroll.querySelectorAll("details"));
const entries = nodes.map((node) => {
const row = node.querySelector<HTMLElement>(":scope > [data-json-row]")!;
const scalar = row.querySelector("[data-json-scalar]")?.textContent ?? "";
if (row.tagName !== "SUMMARY") row.tabIndex = 0;
return { node, row, text: (JSON.parse(node.dataset.key!) + " " + scalar).toLowerCase() };
});
let selected: HTMLElement | undefined;
let selectedValue = payload;
let path = "";
let beforeSearch: Set<HTMLDetailsElement> | undefined;
let matches: HTMLElement[] = [];
let matchIndex = -1;
function select(row: HTMLElement) {
const chain: HTMLElement[] = [];
let node = row.closest<HTMLElement>("[data-json-node]");
while (node && scroll!.contains(node)) {
chain.unshift(node);
node = node.parentElement?.closest("[data-json-node]") ?? null;
}
if (!chain.length) return;
selected?.removeAttribute("data-current");
row.setAttribute("data-current", "");
selected = row;
selectedValue = payload;
path = JSON.parse(chain[0].dataset.key!);
for (const child of chain.slice(1)) {
const key: string = JSON.parse(child.dataset.key!);
if (Array.isArray(selectedValue)) {
path += "[" + key + "]";
selectedValue = selectedValue[Number(key)];
} else if (selectedValue !== null && typeof selectedValue === "object") {
path += /^[A-Za-z_$][\w$]*$/.test(key) ? "." + key : "[" + JSON.stringify(key) + "]";
selectedValue = selectedValue[key];
}
}
pathLabel!.textContent = path;
result!.textContent = "";
fallback!.hidden = true;
}
function searchRows() {
const term = search!.value.trim().toLowerCase();
if (beforeSearch) allBranches.forEach((branch) => { branch.open = beforeSearch!.has(branch); });
if (term && !beforeSearch) beforeSearch = new Set(allBranches.filter((branch) => branch.open));
matches = [];
matchIndex = -1;
for (const { node, row, text } of entries) {
const hit = Boolean(term) && text.includes(term);
row.toggleAttribute("data-match", hit);
if (!hit) continue;
matches.push(row);
let ancestor = node.parentElement?.closest("details");
while (ancestor && scroll!.contains(ancestor)) {
ancestor.open = true;
ancestor = ancestor.parentElement?.closest("details");
}
}
if (!term) beforeSearch = undefined;
count!.textContent = term ? matches.length + (matches.length === 1 ? " match" : " matches") : "";
}
search.addEventListener("input", searchRows);
search.addEventListener("keydown", (event) => {
if (event.key === "Escape") { search.value = ""; search.dispatchEvent(new Event("input", { bubbles: true })); }
if (event.key !== "Enter" || !matches.length) return;
event.preventDefault();
matchIndex = matchIndex < 0 ? (event.shiftKey ? matches.length - 1 : 0) : (matchIndex + (event.shiftKey ? -1 : 1) + matches.length) % matches.length;
select(matches[matchIndex]);
matches[matchIndex].scrollIntoView({ block: "nearest" });
count.textContent = "Match " + (matchIndex + 1) + " of " + matches.length;
});
for (const event of ["focusin", "click"]) {
scroll.addEventListener(event, (e) => {
const row = (e.target as Element).closest<HTMLElement>("[data-json-row]");
if (row) select(row);
});
}
scroll.addEventListener("keydown", (event) => {
const row = (event.target as Element).closest<HTMLElement>("[data-json-row], [data-json-page]");
if (!row || event.altKey || event.ctrlKey || event.metaKey) return;
const branch = row.tagName === "SUMMARY" ? row.parentElement as HTMLDetailsElement : null;
if (!["ArrowDown", "ArrowUp", "ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const visible = rows.filter((element) => {
const inside = element.tagName === "SUMMARY" ? element.parentElement?.parentElement : element.parentElement;
const closed = inside?.closest("details:not([open])");
return !closed || !scroll.contains(closed);
});
const index = visible.indexOf(row);
if (event.key === "Home") visible[0]?.focus();
else if (event.key === "End") visible.at(-1)?.focus();
else if (event.key === "ArrowUp") visible[index - 1]?.focus();
else if (event.key === "ArrowDown") visible[index + 1]?.focus();
else if (event.key === "ArrowRight" && branch) {
if (branch.open) visible[index + 1]?.focus();
else branch.open = true;
} else if (event.key === "ArrowLeft") {
if (branch?.open) branch.open = false;
else {
const parent = (branch ?? row).parentElement?.closest("details");
if (parent && scroll.contains(parent)) parent.querySelector<HTMLElement>(":scope > summary")?.focus();
}
}
});
root.querySelectorAll<HTMLButtonElement>("[data-copy-kind]").forEach((button) => button.addEventListener("click", async () => {
const copyingPath = button.dataset.copyKind === "path";
const text = copyingPath ? path : JSON.stringify(selectedValue, null, 2);
try {
await navigator.clipboard.writeText(text);
result.textContent = copyingPath ? "Path copied." : "Value copied.";
} catch {
fallback.value = text;
fallback.hidden = false;
fallback.focus();
fallback.select();
result.textContent = "Select and copy the text manually.";
}
}));
root.querySelectorAll<HTMLElement>("[data-json-tools]").forEach((el) => { el.hidden = false; });
select(entries[0].row);
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-json-viewer]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-json-viewer-listener")) {
document.documentElement.setAttribute("data-haze-json-viewer-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- Readers inspect nested webhook events or API responses.
- People need to find a field and copy its exact property path or JSON value.
When not to use
- Use code-block for a read-only source listing.
- Use file-tree for project directories.
Installation
Add the Haze registry to components.json once, then install JSON viewer with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/json-viewernpx shadcn@latest add @haze/json-vieweryarn dlx shadcn@latest add @haze/json-viewerbunx --bun shadcn@latest add @haze/json-viewerFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique prefix for the viewer label and search field. |
| data* | JSON value | – | A JSON object, array, string, number, boolean or null. |
| label | string | JSON payload | Visible name of the payload. |
| rootName | string | payload | Root label used when copying property paths. |
| openDepth | number | 1 | Number of nesting levels initially expanded. |
| pageSize | number | 40 | Children per disclosure in a large array or object. |
| class | string | – | Classes applied to the viewer panel. |
Keyboard interactions
- EnterSpace
- Toggle the focused branch or page.
- Arrow keysHomeEnd
- Move across visible rows, open a branch or return to its parent.
- EnterShiftEnter in search
- Select the next or previous match.
Accessibility
- Branches use native summaries. Each key and scalar renders as escaped text.
- Search reports matches politely. A selectable text field is available when copying fails.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "JSON viewer" with `npx shadcn@latest add @haze/json-viewer`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import JsonViewer from "@/components/haze/ui/json-viewer.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/json-viewer.md
Customize with real content
Adapt the Haze json-viewer ui for our product. Replace the demo values of these props with our real content: id, data, label, rootName, openDepth, pageSize, class. Keep the layout, the heading level rules and these accessibility details: Branches use native summaries. Each key and scalar renders as escaped text. Search reports matches politely. A selectable text field is available when copying fails. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using json-viewer, check it fits: use it when readers inspect nested webhook events or api responses.; people need to find a field and copy its exact property path or json value.. Avoid it when use code-block for a read-only source listing.; use file-tree for project directories.. Alternatives: @haze/code-block, @haze/file-tree, @haze/copy-button.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/search-field
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.