Skip to content

JSONViewer ​

A read-only JSON tree viewer with collapse/expand, search, JSONPath copy, fixed-row virtual scrolling, keyboard support and screen-reader semantics. Use it as an embeddable block for API responses, configuration review or log inspection; two instances can sit side by side for comparison.

Basic usage ​

Pass raw JSON through the text attribute. The root is expanded by default (default-expand-depth="1"). String values keep their full text in the DOM; long values are visually ellipsized on one line with the full text in title.

API response

You can also pass an object or array through the data property; whichever of data or text is written last wins. Writing data removes the text attribute, and writing text clears the cached data.

data property channel

Custom expand/collapse icons ​

Provide template[slot="toggle-collapsed"] and template[slot="toggle-expanded"] for the collapsed and expanded states. Templates can contain text, SVG or boxed elements; a missing template falls back to the default triangle, and leaf rows never render an icon. Use part="toggle-icon" inside a template for ::part(toggle-icon) styling, or use inline styles.

Boxed + / − icons (click the root row)

Controlled expansion ​

When the expanded attribute is present the component is controlled: it only emits oas-toggle / oas-expanded-change and never writes the attribute back. Updating expanded from the host re-renders the tree. Paths use single-quoted JSONPath, for example $['data']['users'][0].

expanded controlled by external buttons

Expand allCollapse allRoot only

Controlled expanded: $

Search is case-insensitive and matches object keys and primitive values. Matching automatically expands ancestors without hiding other nodes. The toolbar shows the count and cycles through previous/next matches. Ctrl/Cmd+F focuses search when focus is inside the component; set search-shortcut="false" to disable it.

Search count and auto-expansion

Search state: —

Copy path / value / subtree ​

The toolbar copies the active node's JSONPath, raw value or subtree JSON. You can also call copyPath(), copyValue() or copyJson(). A cancelable oas-copy fires before copying, oas-copied on success and oas-copy-error on failure. copyable="false" hides the buttons but keeps the methods available.

Copy event feedback

Click a toolbar copy button or call an instance method.

js
const viewer = document.querySelector('#jv-copy')
viewer.scrollToPath("$['a.b'][0]['c']")
await viewer.copyPath()   // $['a.b'][0]['c']
await viewer.copyValue()  // hello
await viewer.copyJson()   // "hello"

Large JSON and virtual scrolling ​

Fixed-row virtualization turns on automatically above 200 visible rows, keeping only the rows around the viewport in the DOM. Set virtual="false" to disable it, and use height / row-height to control the viewport and row height. A 10k-node instance still supports search, keyboard navigation and scrollToPath().

10k nodes, viewport-only rendering

Generating data…

Error state and recovery ​

Invalid text shows an error panel and emits oas-parse-error with message plus locatable line / column. Writing valid data or text recovers automatically. Extremely deep nesting that overflows the build/walk stack also enters this recoverable error state (localized message) instead of throwing RangeError at the host; copy failures on over-deep subtrees emit oas-copy-error and show the failure notice.

Parse failure → recover with valid data

Write valid data

Waiting for a parse error…

Display options ​

Use compact for tighter spacing (20px rows and 11px type by default), toolbar="false" to hide the toolbar, copyable="false" to hide copy buttons, search-shortcut="false" to disable the shortcut, indent for copied JSON indentation and aria-label to name the tree. The example below also sets height, row-height, default-expand-depth="2" and virtual="false".

Compact read-only panel

Keyboard and accessibility ​

The tree container is a single tab stop and uses aria-activedescendant for the active row. Rows expose role="treeitem", aria-level, aria-posinset, aria-setsize and aria-expanded. The accessible name supports host aria-label (falling back to “JSON tree”) or aria-labelledby pointing to in-page elements (the referenced elements are resolved across the shadow boundary and written into the tree container: engines supporting ariaLabelledByElements get live references, others fall back to a reference-text snapshot on the container's aria-label — idref does not cross the shadow boundary, so a bare mirror cannot be resolved; missing references fall back to the host aria-label channel, and the snapshot text is not auto-tracked on reference changes).

KeyBehavior
↑ / ↓Previous / next visible row
→Expand a container; when expanded, move into its first child
←Collapse a container; when collapsed, move to its parent
Home / EndFirst / last row
Enter / SpaceToggle the focused container
Ctrl/Cmd+FFocus search while focus is inside

Theme and parts ​

All colors use CSS variable tokens and follow dark mode automatically. Style viewer, toolbar, viewport, row, key, value, twisty, error and copy-status with ::part(). With toolbar="false", copy feedback appears in a bottom-end floating part="copy-status" notice. Indentation uses logical properties in RTL, while JSON text keeps bidi isolation.

Utility functions ​

The pure model helpers are also exported from @oas-ui/ui/data/json-viewer (or @oas-ui/ui) for host-side custom rendering or preprocessing: buildJsonTree, flattenVisible, searchJson, encodeJsonPath, parseJsonPath, collectAncestorPaths, serializeValue, serializeJson. They do not depend on the DOM.

API ​

oas-json-viewer ​

Attributes ​

AttributeDescriptionTypeDefault
aria-labelAccessible name of the tree (defaults to “JSON tree”)——
aria-labelledbyAccessible name mirror (second channel): the host idref list is mirrored as-is to the tree container (removed state cleans up; when both aria-label and aria-labelledby are set, native accessible-name computation gives aria-labelledby precedence)——
compactCompact mode (20px rows, 11px type and tighter toolbar padding by default)——
copyableCopy button switch; false hides buttons while copy methods remain availablestring—
default-expand-depthInitial expand depth: 0 keeps only the root, 1 expands the root (default), and so onstring1
expandedControlled expanded path array (JSON string). When present the component only emits events and never writes backstring[]—
heightViewport height in px (default 360)string360
indentIndent width for copied JSON (default 2)string2
row-heightFixed row height in px (default 24, minimum 20)string—
searchSearch query (case-insensitive substring over keys and primitive values)string—
search-shortcutIntercept Ctrl/Cmd+F to focus search while focus is inside; false disables itstring—
textRaw JSON text (attribute channel; SSR/DSD friendly)string—
toolbarToolbar switch; false hides search, expand and copy buttonsstring—
virtualVirtual scrolling switch; auto by default (enabled above 200 visible rows), false forces it offstring—

Property (JS property; see each row for attribute reflection) ​

PropertyDescriptionTypeDefault
dataObject/array channel (property); whichever of data or text was written last winsJsonValue—
expandedControlled expanded path array property; writing it sets the expanded attributestring[]—
searchSearch query property; writing it reflects the search attributestring—
textRaw JSON property; writing it clears the data cachestring—

Methods ​

MethodSignatureDescription
expandAllexpandAll(): voidExpand every container; controlled mode emits oas-expanded-change
collapseAllcollapseAll(): voidCollapse every container
expandToDepthexpandToDepth(depth: number): voidExpand to the given depth: 0 leaves only the root, 1 root plus children, and so on
scrollToPathscrollToPath(path: string): voidScroll to a JSONPath and transiently expand folded ancestors
searchNextsearchNext(): voidJump to the next search match (cyclic)
searchPrevsearchPrev(): voidJump to the previous search match (cyclic)
copyPathcopyPath(path: string): Promise<boolean>Copy the JSONPath (active node by default)
copyValuecopyValue(path: string): Promise<boolean>Copy the value: raw text for primitives, formatted JSON for containers
copyJsoncopyJson(path: string): Promise<boolean>Copy the subtree JSON (strings stay quoted)

Events ​

EventDescription
oas-copiedFired after a successful copy, detail: { path, kind, text }
oas-copyCancelable event before copying, detail: { path, kind, text }
oas-copy-errorClipboard write failed, detail: { path, kind, text, error }
oas-expanded-changeBulk expand/collapse requested, detail: { paths }; controlled mode waits for the host to write back
oas-parse-errorFired when text cannot be parsed, detail: { message, line?, column?, source }
oas-search-changeSearch state changed, detail: { query, matches, activeIndex }; activeIndex is -1 when nothing matches
oas-toggleFired when a node expands/collapses, detail: { path, expanded }; controlled mode only emits

Slots ​

NameDescription
template[slot="toggle-collapsed"]Collapsed icon template (text, SVG or boxed content; the default triangle is used when absent)
template[slot="toggle-expanded"]Expanded icon template (the default triangle is used when absent; leaf rows render no icon)

CSS Variables ​

CSS VariableDescriptionDefault
--oas-json-viewer-font-sizeCode font size (default 12px)12px
--oas-json-viewer-heightViewport height (default 360px; used when the height attribute is absent)360px
--oas-json-viewer-row-heightRow height (default 24px, accepts CSS lengths; used when row-height/compact is absent)24px

Released under the MIT OR Apache-2.0 License.