/json-viewer

Web Component to visualize JSON data in a tree view

Primary LanguageJavaScriptMIT LicenseMIT

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

A Web Component to visualize JSON data in a tree view


Installation

npm i @alenaksu/json-viewer

Then import the package to your project.

import '@alenaksu/json-viewer';

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 | Mantains 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.

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 dinamically

<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();

Theming

The appereance of the component can be modified by changing the CSS variables

json-viewer {
    /* Background, font and color */
    --background-color: #2a2f3a;
    --color: #f8f8f2;
    --font-family: monaco, Consolas, 'Lucida Console', monospace;

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

    /* Collapsed node preview */
    --preview-color: rgba(222, 175, 143, 0.9);

    /* Search highlight color */
    --highlight-color: #6fb3d2;
}

Demo

The demo can also be run locally with

npm run start