JSFiddle - React, Tailwind, and code Playground
HTML
Examples:
<p>{"key": "val", "recur" : { "obj1": "val1", "obj2": "val2"}}</p>
<p>{"key": "val", "recur" : { "obj1": "val1", "obj2": "val2", "obj3": {"key": "val", "recur" : { "obj1": "val1", "obj2": "val2"}}}}</p>
<div id="wrapper">
<textarea name="input" id="jsonInput" placeholder="enter json here"></textarea>
<div id="jsonOutput"></div>
</div>
<p>
<button id="apply">Apply</button>
</p>
CSS
#wrapper {
float: left;
width: 100%;
}
#jsonInput, #jsonOutput {
width: 500px;
float: left;
margin: 20px;
}
/* explorer css */
.json-explorer {
background: #eee;
padding: 20px;
border: 1px solid silver;
}
.json-explorer ul {
list-style-type: none;
margin: 0px;
font-size: 18px;
}
.json-explorer li {
position: relative;
line-height: 20px;
}
.json-explorer li:before {
content: '\2022';
position: absolute;
left: -15px;
width: 100%;
}
.json-explorer li.parent {
cursor: pointer;
}
.json-explorer li.parent:before {
content: '\25B6';
font-size: .5em;
display: block;
cursor: pointer;
}
.json-explorer li.parent.expanded:before {
content: '\25BC';
}
.json-explorer li.parent > ul {
display: none;
cursor: auto;
}
.json-explorer li.parent.expanded > ul {
display: block;
}
/* theming */
.json-explorer .key {
color: #334D5C;
}
.json-explorer .value {
color: #45B29D;
}
JavaScript
document.getElementById('apply').addEventListener('click', function() {
init(JSON.parse(document.getElementById('jsonInput').value), document.getElementById('jsonOutput'))
})
function init(obj, el) {
el.innerHTML = '';
el.className = "json-explorer"
el.addEventListener('click', function (e) {
if (e.target.classList.contains('parent')) {
e.target.classList.toggle('expanded')
}
})
function buildList(parentObj, parentEl) {
var rEl, rParent;
rParent = document.createElement('ul');
for (var key in parentObj) {
rEl = document.createElement('li');
if (typeof parentObj[key] == "object") {
rEl.className = parentObj[key] instanceof Array ? 'parent array' : 'parent';
rEl.innerHTML = '<span class="key">' + key + '</span>: {'
buildList(parentObj[key], rEl)
} else {
rEl.innerHTML = '<span class="key">' + key + '</span>: <span class="value">' + parentObj[key] + '</span>';
}
rParent.appendChild(rEl);
}
parentEl.appendChild(rParent);
}
buildList(obj, el);
}