JSON Viewer & Path Picker In Vanilla JavaScript

Category: Javascript | March 27, 2022
Author:ryshu
Views Total:1,286 views
Official Page:Go to website
Last Update:March 27, 2022
License:MIT

Preview:

JSON Viewer & Path Picker In Vanilla JavaScript

Description:

This is the Vanilla JavaScript version of the jQuery JSON Path Picker, which helps you render your JSON data in a collapsible tree structure where you can get the path to each key by clicking on the output icon.

How to use it:

Load the stylesheet jsonpath-picker.min.css and JavaScript jsonpath-picker.min.js in the html file.

<link href="/jsonpath-picker.min.css" rel="stylesheet" />
<script src="/jsonpath-picker.min.js"></script>

Create a container in which the library generate the tree.

<pre id="json-renderer" class="json-tree"></pre>

Create an input filed to display the JSON path.

<input class="path" type="text">

Create a button to generate the tree.

<button id="btn-json-path-picker" class="generate-button">
  Generate tree
</button>

Create a container to accept JSON data.

<textarea id="json-input" class="json-input" autofocus placeholder="Paste JSON here!"></textarea>

The JavaScript to render a JSON tree.

function script() {
  const $pathTarget = document.querySelectorAll('.path');
  const $source = document.querySelector('#json-renderer');
  const defaultOpts = {
        // options here
  };
  function transformJson() {
    let jsonData = null;
    try {
      jsonData = document.querySelector('#json-input').value;
      jsonData = JSON.parse(jsonData);
    } catch (error) {
      alert(`Cannot eval JSON: ${error}`);
      return;
    }
    JPPicker.render($source, jsonData, $pathTarget, defaultOpts);
  }
  document.querySelector('#btn-json-path-picker').addEventListener('click', transformJson);
}
script();

Possible options.

// collapses all nodes on init
outputCollapsed: false,
// keys with quotes
outputWithQuotes: false,
// 'dots' or 'brackets'
pathNotation: 'dots',
// 'single' or 'double'
pathQuotesType: 'single',
// allows the user to process keys
processKeys: false 
keyReplaceRegexPattern: undefined 
keyReplaceRegexFlags: undefined 
keyReplacementText: ''

Changelog:

v1.2.3 (03/27/2022)

  • fix: security issue

You Might Be Interested In:


Leave a Reply