Plus · JsonViewer

JsonViewer

Used for displaying and editing JSON data

When to use

The JsonViewer component can be used for the display and editing of JSON data.

Semi mainly referred to the design concept of the text-buffer data structure of VS Code, reused some utilities and data type definitions (Token parsing, language services, etc.), and implemented the JsonViewer component in combination with our functional/style customization requirements. Visually, it will be more coordinated with other components within the Semi Design Next system, and it will be more convenient for customized rendering and customization of specific data types.

Compared with directly using MonacoEditor, Semi JsonViewer has additional processing in engineering construction, is simpler to use, and there is no need to pay attention to complex configurations such as Webpack plugins and worker loaders. At the same time, since we only focus on the JSON data format, it is more lightweight. While being ready to use out of the box, it has a smaller size (📦-96%), a more extreme loading speed (🚀 -53.5%), and less memory occupation (⬇️71.6% reduction). For data with five million lines and below, data loading and parsing can be completed within 1 second.

Detailed comparison data can be referred to in the Performance section.

  • If you only need to preview/edit JSON and don't need to modify other more complex programming languages, we recommend that you choose JsonViewer.
  • If you also need to handle data/code files in other formats and the full capabilities of a code editor (syntax highlighting, code completion, error prompts, complex editing, etc.) are essential and the build product size is not a key concern, we recommend that you choose Monaco Editor.

Demos

How to import

import { Button, Image, JsonViewer, Popover, Rating, Tag } from '@fibrous/semi-ui-solid';

Basic Usage

Basic usage of JsonViewer. Pass height and width to set the height and width of the component, and pass the JSON string through value as the initial value. onChange is called with the editor's current text when the content changes. The editor is re-created only when value becomes different from the editor's current content, so writing the onChange text back into value keeps the caret; while value stays the same, the editor keeps what the user typed. To read the value, call getValue() through a ref, please refer to Methods for details.

Code
import { JsonViewer } from '@fibrous/semi-ui-solid';

const data = `{
    "name": "Semi",
    "version": "0.0.0"
}`;

export default function JsonViewerDemo() {
    return (
        <div style={{ 'margin-bottom': '16px' }}>
            <JsonViewer height={100} width={700} value={data} />
        </div>
    );
}

Different lineHeight

Configure the lineHeight parameter of options to set a fixed line height (unit: px, default 20).

Code
import { JsonViewer } from '@fibrous/semi-ui-solid';

const data = `{
    "name": "Semi",
    "version": "0.0.0"
}`;

export default function JsonViewerDemo() {
    return (
        <div>
            <div style={{ 'margin-bottom': '12px', overflow: 'hidden' }}>
                <JsonViewer height={100} width={700} value={data} options={{ lineHeight: 20 }} />
            </div>
            <div style={{ 'margin-bottom': '12px', overflow: 'hidden' }}>
                <JsonViewer height={120} width={700} value={data} options={{ lineHeight: 24 }} />
            </div>
            <div style={{ 'margin-bottom': '12px', overflow: 'hidden' }}>
                <JsonViewer height={120} width={700} value={data} options={{ lineHeight: 26 }} />
            </div>
        </div>
    );
}

Autowrap

Configure the autoWrap parameter of options. When it is set to true, the component will automatically wrap lines according to the length of the content.

Code
import { JsonViewer } from '@fibrous/semi-ui-solid';

const data = `{
    "name": "Semi",
    "version": "0.0.0",
    "description": "Semi Design is a design system that defines a set of mid_back design and front_end basic components."
}`;

export default function JsonViewerDemo() {
    return (
        <div style={{ 'margin-bottom': '16px' }}>
            <JsonViewer height={120} width={700} value={data} options={{ autoWrap: true }} />
        </div>
    );
}

Format options

Configure options.formatOptions to set the formatting configuration of the component.

  • tabSize: number,set the indent size to 4, which means each level of indentation is 4 spaces.
  • insertSpaces: boolean,when it is true, it means using spaces for indentation, and when it is false, it means using tabs.
  • eol: string,set the line break character, which can be \n,\r\n,
Code
import { Button, JsonViewer, type JsonViewerElement } from '@fibrous/semi-ui-solid';

const data = `{
  "name": "Semi",
  "version": "0.0.0"
}`;

export default function JsonViewerDemo() {
    let jsonViewer: JsonViewerElement | undefined;

    return (
        <div>
            <Button onClick={() => console.log(jsonViewer?.format())}>格式化</Button>
            <div style={{ 'margin-bottom': '16px', 'margin-top': '16px' }}>
                <JsonViewer ref={(node) => (jsonViewer = node)} height={100} width={700} value={data} options={{ formatOptions: { tabSize: 4, insertSpaces: true, eol: '\n' } }} />
            </div>
        </div>
    );
}

Custom Render Rules

By configuring the options.customRenderRule parameter, you can customize how JSON content is rendered (Note: only works in read-only mode).

Behavior notes

path in customRenderRule is computed more accurately: the key token and the value token of the same key-value pair share the same path (they both map to the property path, e.g. root.<key>).

As a result, rules that only rely on path (such as path === 'root.<key>') may match both the key and the value, which can change which rule “wins” compared to previous versions.

If you want to match only the key or only the value, use the third argument tokenType of function match:

const targetPath = 'root.<key>';
// Key only
match: (_value, path, tokenType) => tokenType === 'key' && path === targetPath;
// Value only
match: (value, path, tokenType) => tokenType === 'value' && path === targetPath;

customRenderRule is an array of rules, where each rule contains two properties:

  • match: Matching condition, can be one of three types:
    • String: Exact match
    • Regular expression: Match by regex
    • Function: Custom matching logic, with signature (value: string | number | boolean | null, path: string, tokenType: 'key' | 'value') => boolean
      • value: Value to match (JSON key or value). When match is a function, value will be passed as the parsed primitive when possible (number / boolean / null / string), so strict comparisons like === work; when match is a string or RegExp, matching is still based on textual content (string tokens are unquoted)
      • path: Current matching path, format is root.key1.key2.key3[0].key4
      • tokenType: Current token type, 'key' for JSON property name, 'value' for JSON value. Useful for distinguishing between key and value matching
  • render: Custom render function, with signature (content: string) => JSX.Element
    • content: Matched content. For string values, includes double quotes (e.g., "name", "Semi")
    • Returning null, undefined or false skips custom rendering and keeps the token text, so (content) => cond && <X /> works
Code
import { Image, JsonViewer, Popover, Rating, Tag, type JsonViewerCustomRenderRule } from '@fibrous/semi-ui-solid';

const data = `{
  "name": "Semi",
  "version": "2.7.4",
  "rating": 5,
  "tags": ["design", "react", "ui"],
  "image": "/assets/root-web-sites/abstract.jpg"
}`;

const customRenderRule: JsonViewerCustomRenderRule[] = [
    {
        match: 'Semi',
        render: (content) => (
            <Popover showArrow content="我是用户自定义的渲染" trigger="hover">
                <span>{content}</span>
            </Popover>
        ),
    },
    {
        match: (value) => value == 5,
        render: (content) => <Rating defaultValue={Number(content)} size={10} disabled />,
    },
    {
        match: (_value, path) => path === 'root.tags[0]' || path === 'root.tags[1]' || path === 'root.tags[2]',
        render: (content) => (
            <Tag size="small" shape="circle">
                {content}
            </Tag>
        ),
    },
    {
        match: new RegExp('^http'),
        render: (content) => {
            // content is the raw string token with its quotes; without them it is a valid URL
            return (
                <Popover showArrow content={<Image width={100} height={100} src={content.replace(/^"|"$/g, '')} />} trigger="hover">
                    <span>{content}</span>
                </Popover>
            );
        },
    },
];

export default function JsonViewerDemo() {
    return (
        <div>
            <div style={{ 'margin-bottom': '16px', 'margin-top': '16px' }}>
                <JsonViewer
                    height={200}
                    width={600}
                    value={data}
                    showSearch={false}
                    options={{
                        formatOptions: { tabSize: 4, insertSpaces: true, eol: '\n' },
                        customRenderRule,
                        readOnly: true,
                        autoWrap: true,
                    }}
                />
            </div>
        </div>
    );
}

Custom Search Button

Use the renderSearchButton property to customize the rendering of the search button, enabling fixed positioning, custom styles, and more. The first argument creates the default button: call defaultButton() where the returned JSX places it; showSearchBar on the second argument controls is a getter and must be read inside the returned JSX so that it stays in sync with the search bar.

Code
import { Show } from 'solid-js';
import { IconSearch } from '@fibrous/semi-icons-solid';
import { Button, JsonViewer } from '@fibrous/semi-ui-solid';

const data = `{
    "name": "Semi",
    "version": "0.0.0"
}`;

export default function JsonViewerDemo() {
    return (
        <div style={{ 'margin-bottom': '16px' }}>
            <JsonViewer
                height={200}
                width={700}
                value={data}
                renderSearchButton={(defaultButton, controls) => (
                    <div style={{ position: 'absolute', top: '10px', right: '10px', 'z-index': '10' }}>
                        <Show when={!controls.showSearchBar} fallback={defaultButton()}>
                            <Button icon={<IconSearch />} onClick={controls.onToggleSearchBar}>
                                搜索
                            </Button>
                        </Show>
                    </div>
                )}
            />
        </div>
    );
}

API Reference

JsonViewer

Props

PropertyDescriptionTypeDefault
heightHeight. A number is taken as px; a string is used as is.number | string400
limitSearchButtonBoundsWhether to limit the drag range of the search button to the component container.boolean-
onChangeCalled with the editor's current text when the content changes.Type(value: string) => void-
optionsEditor configuration, fields described by JsonViewerOptions. The defaults of ariaLabel, readOnly and autoWrap are merged per key, so passing some fields keeps the defaults of the rest. A change in options, compared deeply, re-creates the editor; mutating nested objects such as formatOptions or customRenderRule in place is not noticed, so replace them with new objects.JsonViewerOptions-
refThe root element, typed JsonViewerElement, which carries the JsonViewerHandle methods.TypeRef<JsonViewerElement>-
renderSearchButtonCustom render for the search button. The first argument creates the default button: call it where the button is inserted. The second is controls, holding the search state and methods. controls.showSearchBar is a getter and must be read inside the returned JSX.Type(defaultSearchButton: () => JSX.Element, searchControls: JsonViewerSearchControls) => JSX.Element-
showSearchWhether to show the search button.booleantrue
valueJSON text to show and edit; the editor starts empty when omitted. The editor is re-created only when value becomes different from its current content, so writing the onChange value back keeps the caret.string""
widthWidth. A number is taken as px; a string is used as is.number | string400

Methods

MethodDescriptionType
formatFormats the current content with formatOptions.Type() => void
getSearchResultsGets the current search results.Type() => ReturnType<JsonViewerFoundation['getSearchResults']>
getStyleReturns the current width and height.Type() => { width: number | string; height: number | string }
getValueGets the editor's current text.Type() => string
nextSearchMoves to the next search result, with an optional step.Type(step?: number) => void
prevSearchMoves to the previous search result, with an optional step.Type(step?: number) => void
replaceReplaces the current search match; an empty replacement deletes the match, and nothing happens when there is no match or the viewer is read-only.Type(replaceText: string) => void
replaceAllReplaces all search matches; an empty replacement deletes them all, and nothing happens when the viewer is read-only.Type(replaceText: string) => void
searchSearches for text; the optional arguments control case sensitivity, whole-word matching and regular expressions.Type(searchText: string, caseSensitive?: boolean, wholeWord?: boolean, regex?: boolean) => void

class, style, ref and native attributes fall on the root element. When the root has no role and aria-label or aria-labelledby is passed, the root gets role="group"; an explicit role wins.

JsonViewerOptions

AttributeDescriptionTypeDefault
lineHeightHeight of each line of content, unit:pxnumber20
autoWrapWhether to wrap lines automatically.booleantrue
readOnlyWhether to be read-only.booleanfalse
customRenderRuleCustom render rulesCustomRenderRule[]-
formatOptionsContent format settingFormattingOptions-
completionOptionsAuto-completion settingCompletionOptions-
ariaLabelAccessible name of the content area (the read-only scroll region, or the editable textbox)stringlocale JsonViewer.content

CustomRenderRule

The type is named JsonViewerCustomRenderRule, and render returns a JSX element.

AttributeDescriptionTypeDefault
matchMatching rulestring | RegExp | (value: string | number | boolean | null, path: string, tokenType: 'key' | 'value') => boolean-
renderRender function(content: string) => JSX.Element-

FormattingOptions

AttributeDescriptionTypeDefault
tabSizeIndent sizenumber4
insertSpacesWhether to use spaces for indentationbooleantrue
eolLine break characterstring'\n'

CompletionOptions

AttributeDescriptionTypeDefault
staticCompletionsStatic completion items. They are appended only after the candidates inferred from the document structure, and are not offered when nothing can be inferred; an item whose label matches an existing candidate is not added again. Only label, insertText (falling back to label) and documentation of each item are readCompletionItem[]-

SearchControls

When using renderSearchButton, the second parameter controls contains the following properties:

AttributeDescriptionType
showSearchBarWhether the search bar is currently visibleboolean
onToggleSearchBarToggle search bar visibility() => void
onSearchExecute search(text: string, caseSensitive?: boolean, wholeWord?: boolean, regex?: boolean) => void
onPrevSearchNavigate to previous search result() => void
onNextSearchNavigate to next search result() => void
onReplaceReplace current search match(text: string) => void
onReplaceAllReplace all search matches(text: string) => void

Methods

The root element that ref receives (type JsonViewerElement) carries the methods in the table below, which can be called directly, for example jsonViewer?.format().

MethodDescription
getValue()Get current value
format()Format current content
search(searchText: string, caseSensitive?: boolean, wholeWord?: boolean, regex?: boolean)Search for text with optional parameters
getSearchResults()Get current search results
prevSearch(step?: number)Navigate to previous search result, with optional step size
nextSearch(step?: number)Navigate to next search result, with optional step size
replace(replaceText: string)Replace current search match
replaceAll(replaceText: string)Replace all search matches
getStyle()Get the current width and height

Performance

Bundle Size

Libs NameSizeSize (Gzip)
JsonViewer203.14kb51.23kb
MonacoEditor5102.0 KB1322.7 KB

Time for rendering data of different magnitudes.

For details on the generation method of the test data, please refer to URL
When the data volume exceeds 500,000 lines, ReactMonacoEditor turns off highlighting and other behaviors by default, and the data comparison does not follow the principle of a single variable.

Libs Name1k lines5k lines10 thousand lines100 thousand lines500 thousand lines1 million lines3 million lines
JsonViewer30.42ms30.66ms36.87ms52.73ms111.02ms178.81ms506.25ms
ReactMonacoEditor72.01ms73.76ms76.64ms97.89ms133.31ms202.79ms495.53ms
Performance improvement57.70%58.41%51.87%46.11%---