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 { JsonViewer } from '@fibrous/semi-ui-react';
Basic Usage
Basic usage of JsonViewer. Pass in the height and width parameters to set the height, width and initial value of the component. Pass in the JSON string through the 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 (setState) keeps the caret; while value stays the same, the editor keeps what the user typed. If you need to get the component's value, you can get it through ref, please refer to Methods for details.
Code
import { JsonViewer } from '@fibrous/semi-ui-react';
const data = `{
"name": "Semi",
"version": "0.0.0"
}`;
export default function JsonViewerDemo() {
return (
<div style={{ marginBottom: 16 }}>
<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-react';
const data = `{
"name": "Semi",
"version": "0.0.0"
}`;
export default function JsonViewerDemo() {
return (
<div>
<div style={{ marginBottom: 12, overflow: 'hidden' }}>
<JsonViewer height={100} width={700} value={data} options={{ lineHeight: 20 }} />
</div>
<div style={{ marginBottom: 12, overflow: 'hidden' }}>
<JsonViewer height={120} width={700} value={data} options={{ lineHeight: 24 }} />
</div>
<div style={{ marginBottom: 12, 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-react';
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={{ marginBottom: 16 }}>
<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 { useRef } from 'react';
import { JsonViewer, Button, type JsonViewerHandle } from '@fibrous/semi-ui-react';
const data = `{
"name": "Semi",
"version": "0.0.0"
}`;
export default function JsonViewerDemo() {
const jsonviewerRef = useRef<JsonViewerHandle>(null);
return (
<div>
<Button onClick={() => console.log(jsonviewerRef.current?.format())}>格式化</Button>
<div style={{ marginBottom: 16, marginTop: 16 }}>
<JsonViewer ref={jsonviewerRef} 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
pathincustomRenderRuleis computed more accurately: the key token and the value token of the same key-value pair share the samepath(they both map to the property path, e.g.root.<key>).As a result, rules that only rely on
path(such aspath === '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
tokenTypeof 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') => booleanvalue: Value to match (JSON key or value). Whenmatchis a function,valuewill be passed as the parsed primitive when possible (number / boolean / null / string), so strict comparisons like===work; whenmatchis a string or RegExp, matching is still based on textual content (string tokens are unquoted)path: Current matching path, format isroot.key1.key2.key3[0].key4tokenType: 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) => React.ReactNodecontent: Matched content. For string values, includes double quotes (e.g.,"name","Semi")- Returning
null,undefinedorfalseskips custom rendering and keeps the token text, so(content) => cond && <X />works
Code
import { JsonViewer, Rating, Popover, Tag, Image, type JsonViewerCustomRenderRule as CustomRenderRule } from '@fibrous/semi-ui-react';
const data = `{
"name": "Semi",
"version": "2.7.4",
"rating": 5,
"tags": ["design", "react", "ui"],
"image": "/assets/root-web-sites/abstract.jpg"
}`;
export default function JsonViewerDemo() {
const customRenderRule: CustomRenderRule[] = [
{
match: 'Semi',
render: (content) => {
return (
<Popover showArrow content="我是用户自定义的渲染" trigger="hover">
<span>{content}</span>
</Popover>
);
},
},
{
match: (value) => value == 5,
render: (content) => {
return <Rating defaultValue={Number(content)} size={10} disabled />;
},
},
{
match: (_value, path) => path === 'root.tags[0]' || path === 'root.tags[1]' || path === 'root.tags[2]',
render: (content) => {
return (
<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>
);
},
},
];
return (
<div>
<div style={{ marginBottom: 16, marginTop: 16 }}>
<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.
Code
import { IconSearch } from '@fibrous/semi-icons-react';
import { JsonViewer, Button } from '@fibrous/semi-ui-react';
const data = `{
"name": "Semi",
"version": "0.0.0"
}`;
export default function JsonViewerDemo() {
return (
<div style={{ marginBottom: 16 }}>
<JsonViewer
height={200}
width={700}
value={data}
renderSearchButton={(defaultButton, controls) => (
<div style={{ position: 'absolute', top: 10, right: 10, zIndex: 10 }}>
{!controls.showSearchBar ? (
<Button icon={<IconSearch />} onClick={controls.onToggleSearchBar}>
搜索
</Button>
) : (
defaultButton
)}
</div>
)}
/>
</div>
);
}API Reference
JsonViewer
Props
| Property | Description | Type | Default |
|---|---|---|---|
| className | Class name of the root element. | string | - |
| height | Height. A number is taken as px; a string is used as is. | number | string | 400 |
| limitSearchButtonBounds | Whether to limit the drag range of the search button to the component container. | boolean | - |
| onChange | Called with the editor's current text when the content changes. | Type(value: string) => void | - |
| options | Editor configuration, fields described by JsonViewerOptions. ariaLabel falls back to the JsonViewer.content locale text, and readOnly and autoWrap default to false and true. The three 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 | - |
| ref | Handle of the component, typed JsonViewerHandle; its methods are listed under Methods below. It is not the root DOM element. | TypeReact.Ref<JsonViewerHandle> | - |
| renderSearchButton | Custom render for the search button. The first argument is the default button as a ReactNode, which can be placed in the returned content; the second is searchControls, holding the search state and methods. showSearchBar is the value at render time, and the component re-renders when it changes. | Type( defaultSearchButton: React.ReactNode, searchControls: { showSearchBar: boolean; onToggleSearchBar: () => void; onSearch: (text: string, caseSensitive?: boolean, wholeWord?: boolean, regex?: boolean) => void; onPrevSearch: () => void; onNextSearch: () => void; onReplace: (text: string) => void; onReplaceAll: (text: string) => void; } ) => React.ReactNode | - |
| showSearch | Whether to show the search button. | boolean | true |
| style | Inline style of the root element. Its properties override the width, height and position the component sets. | React.CSSProperties | - |
| value | JSON text to show and edit; empty when omitted. The editor is re-created only when value differs from its current content, so writing the onChange value back keeps the caret, focus and undo history. | string | "" |
| width | Width. A number is taken as px; a string is used as is. | number | string | 400 |
Methods
| Method | Description | Type |
|---|---|---|
| format | Formats the current content with formatOptions. | Type() => void |
| getSearchResults | Gets the current search results. | Type() => ReturnType<JsonViewerFoundation['getSearchResults']> |
| getStyle | Returns the current width and height. | Type() => { width: number | string; height: number | string } |
| getValue | Gets the editor's current text. | Type() => string |
| nextSearch | Moves to the next search result, with an optional step. | Type(step?: number) => void |
| prevSearch | Moves to the previous search result, with an optional step. | Type(step?: number) => void |
| replace | Replaces 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 |
| replaceAll | Replaces all search matches; an empty replacement deletes them all, and nothing happens when the viewer is read-only. | Type(replaceText: string) => void |
| search | Searches for text; the optional arguments control case sensitivity, whole-word matching and regular expressions. | Type(searchText: string, caseSensitive?: boolean, wholeWord?: boolean, regex?: boolean) => void |
className, style and other native attributes (such as id and aria-label) 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
| Attribute | Description | Type | Default |
|---|---|---|---|
| lineHeight | Height of each line of content, unit:px | number | 20 |
| autoWrap | Whether to wrap lines automatically. | boolean | true |
| readOnly | Whether to be read-only. | boolean | false |
| customRenderRule | Custom render rules | CustomRenderRule[] | - |
| formatOptions | Content format setting | FormattingOptions | - |
| completionOptions | Auto-completion setting | CompletionOptions | - |
| ariaLabel | Accessible name of the content area (the read-only scroll region, or the editable textbox) | string | locale JsonViewer.content |
CustomRenderRule
| Attribute | Description | Type | Default |
|---|---|---|---|
| match | Matching rule | string | RegExp | (value: string | number | boolean | null, path: string, tokenType: 'key' | 'value') => boolean | - |
| render | Render function | (content: string) => React.ReactNode | - |
FormattingOptions
| Attribute | Description | Type | Default |
|---|---|---|---|
| tabSize | Indent size | number | 4 |
| insertSpaces | Whether to use spaces for indentation | boolean | true |
| eol | Line break character | string | '\n' |
CompletionOptions
| Attribute | Description | Type | Default |
|---|---|---|---|
| staticCompletions | Static 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 read | CompletionItem[] | - |
SearchControls
When using renderSearchButton, the second parameter searchControls contains the following properties:
| Attribute | Description | Type |
|---|---|---|
| showSearchBar | Whether the search bar is currently visible | boolean |
| onToggleSearchBar | Toggle search bar visibility | () => void |
| onSearch | Execute search | (text: string, caseSensitive?: boolean, wholeWord?: boolean, regex?: boolean) => void |
| onPrevSearch | Navigate to previous search result | () => void |
| onNextSearch | Navigate to next search result | () => void |
| onReplace | Replace current search match | (text: string) => void |
| onReplaceAll | Replace all search matches | (text: string) => void |
Methods
Methods bound to the component instance can be called via ref to achieve certain special interactions.
| Method | Description |
|---|---|
| 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 Name | Size | Size (Gzip) |
|---|---|---|
| JsonViewer | 203.14kb | 51.23kb |
| MonacoEditor | 5102.0 KB | 1322.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 Name | 1k lines | 5k lines | 10 thousand lines | 100 thousand lines | 500 thousand lines | 1 million lines | 3 million lines |
|---|---|---|---|---|---|---|---|
| JsonViewer | 30.42ms | 30.66ms | 36.87ms | 52.73ms | 111.02ms | 178.81ms | 506.25ms |
| ReactMonacoEditor | 72.01ms | 73.76ms | 76.64ms | 97.89ms | 133.31ms | 202.79ms | 495.53ms |
| Performance improvement | 57.70% | 58.41% | 51.87% | 46.11% | - | - | - |