@alenaksu/json-viewer

中文文档
2.1.2发布于 2024/10/29MITTypeScriptES Module近 30 天下载 6.8万

GitHub release npm [![downlo

原始使用文档
文档目录14 节
  1. Installation
  2. From CDN
  3. From NPM
  4. Usage
  5. Attributes
  6. Properties
  7. Methods
  8. CSS Parts
  9. CSS custom properties
  10. Basic Usage
  11. Load the JSON dynamically
  12. Basic interactions
  13. Custom renderer
  14. Demo

GitHub release npm downloads Known Vulnerabilities MIT licensed Published on webcomponents.org

A Web Component to visualize JSON data in a tree view


Installation

From CDN

The package contains a bundled version of the component which includes also the Lit library. It can be useful in case you want to import the package using a CDN.

<script src="https://unpkg.com/@alenaksu/[email protected]/dist/json-viewer.bundle.js"></script>

From NPM

Install the component through NPM:

npm i @alenaksu/json-viewer

Import the package to your project, this way the component will be automatically defined in the custom elements registry with its default tag name json-viewer.

import '@alenaksu/json-viewer';

If you want to extend the component or if you just need to use it in scoped registries with a different tag name, then you can import the component class from the package:

import { JsonViewer } '@alenaksu/json-viewer/JsonViewer.js';

class MyJsonViewer extends JsonViewer {
    ...
}

customElements.define('my-json-viewer', MyJsonViewer);

Usage

<json-viewer></json-viewer>

Attributes

  • data - the string representation of JSON object to load

Properties

  • data - get/set the JSON object

Methods

  • filter (regexOrPath: RegExp|string) => void | Maintains only the nodes that match the given criteria
  • resetFilter () => void | Clear the filter
  • expand (regexOrPath: RegExp|string) => void | Expand all the nodes that match the given criteria
  • expandAll () => void | Alias for expand('**')
  • collapse (regexOrPath: RegExp|string) => void | Collapse all the nodes that match the given criteria
  • collapseAll () => void | Alias for collapse('**')
  • search (regexOrPath: RegExp|string) => Iterator | Return and iterator with which is possible to go through all the matched nodes. It scrolls the page to the node and highlights it.

CSS Parts

  • object - The object wrapper element.
  • property - The wrapper element of a property.
  • key - The key element of a property.
  • primitive - The primitive value.
  • primitive--string - Applied when the primitive is a string.
  • primitive--number - Applied when the primitive is a number.
  • primitive--boolean - Applied when the primitive is a boolean.
  • primitive--null - Applied when the primitive is a null.
  • preview - The value preview of a property.
  • highlight - The highlighted value.

CSS custom properties

The appearance of the component can be modified by changing the CSS custom properties

json-viewer {
    /* Background, font and indentation */
    --background-color: #2a2f3a;
    --color: #f8f8f2;
    --font-family: Nimbus Mono PS, Courier New, monospace;
    --font-size: 1rem;
    --line-height: 1.2rem;
    --indent-size: 0.5em;
    --indentguide-size: 1px;
    --indentguide-style: solid;
    --indentguide-color: #333;
    --indentguide-color-active: #666;
    --indentguide: var(--indentguide-size) var(--indentguide-style) var(--indentguide-color);
    --indentguide-active: var(--indentguide-size) var(--indentguide-style) var(--indentguide-color-active);
    --outline-color: #e0e4e5;
    --outline-width: 1px;
    --outline-style: dotted;

    /* Types colors */
    --string-color: #a3eea0;
    --number-color: #d19a66;
    --boolean-color: #4ba7ef;
    --null-color: #df9cf3;
    --property-color: #6fb3d2;

    /* Collapsed node preview */
    --preview-color: #deae8f;

    /* Search highlight color */
    --highlight-color:  #c92a2a;
}

Basic Usage

Put the JSON inside the element

<json-viewer>
    { "quiz": { "sport": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls",
    "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" } }, "maths": { "q1": {
    "question": "5 + 7 = ?", "options": [ "10", "11", "12", "13" ], "answer": "12" }, "q2": { "question": "12 - 8 = ?",
    "options": [ "1", "2", "3", "4" ], "answer": "4" } } } }
</json-viewer>

Load the JSON dynamically

<json-viewer id="json"></json-viewer>

<script>
    document.querySelector('#json').data = { prop1: true, prop2: 'test' };
</script>

Basic interactions

const viewer = document.querySelector('#json');

// Expand/collapse/filter
viewer.expand('**.name');
viewer.collapse(/name/);
viewer.filter('test.*.name');

// Search
const searchIterator = viewer.search('value');
// Scrolls to the node and highlight the value
searchIterator.next();

Custom renderer

This is an experimental feature and it may change in the future

The rendering of the values can be customized by defining a static method customRenderer in the custom element class. The function receives the value and the path of the node and it should return a HTML node or a Lit's TemplateResult object.

import { JsonViewer } from '@alenaksu/json-viewer/JsonViewer.js';

customElements.define(
    'json-viewer',
    class extends JsonViewer {
        static styles = [
            JsonViewer.styles,
            css`
                a {
                    color: white;
                    text-decoration: underline;
                }
            `
        ];

        static customRenderer(value, path) {
            if (typeof value === 'string') {
                if (URL.canParse(value)) {
                    return html`<a href="${value}" target="_blank">${value}</a>`;
                } else if (Date.parse(value)) {
                    return new Date(value).toLocaleString();
                }
            } else if (typeof value === 'number') {
                return value.toFixed(2);
            }

            return super.customRenderer(value);
        }
    }
);

Demo

The demo can also be run locally with

npm run start

版本与发布记录

@alenaksu/json-viewer 共发布 24 个版本,首次发布于 2019/08/04;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.1.2latest2024/10/292 年前
2.1.12024/10/102 年前
2.1.02024/10/082 年前
2.0.12023/04/133 年前
2.0.02022/10/064 年前
1.0.12022/06/204 年前

关于 @alenaksu/json-viewer 的常见问题

@alenaksu/json-viewer 是什么?

[![downlo

如何安装 @alenaksu/json-viewer?

在项目目录运行 npm install @alenaksu/json-viewer,或使用 pnpm add / yarn add / bun add。

@alenaksu/json-viewer 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@alenaksu/json-viewer 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@alenaksu/json-viewer 可以商用吗?

@alenaksu/json-viewer 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@alenaksu/json-viewer 的下载量有多少?

根据 npm 官方下载统计,@alenaksu/json-viewer 在 2026/10/06 – 2026/11/04 这 30 天内被下载 67,506 次,日均约 2,250 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@alenaksu/json-viewer 还在维护吗?

最新版本 2.1.2 发布于 2024/10/29(2 年前);至今共发布 24 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/08/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。