Skip to content

Instantly share code, notes, and snippets.

@eyalzek
Last active August 29, 2015 14:16
Show Gist options
  • Save eyalzek/8e2a456b0818b07652af to your computer and use it in GitHub Desktop.
Save eyalzek/8e2a456b0818b07652af to your computer and use it in GitHub Desktop.
Pretty print nested json with optional collapsible rows and methods for getting and setting to the original json object.
function jsonToHtml(json) {
console.log('complete json', _.keys(json));
$('.json-container').append('{');
_.each(_.keys(json), function(key, index) {
$('.json-container').append(createBlock(key, json[key]));
});
$('.json-container').append('}');
}
function createBlock(key, value, ids) {
var html = $('<div>', {
'class': 'row',
}),
id = ids || key;
if (_.isObject(value)) {
_.isArray(value) ? html.append('<span class="key collapse">'+ key +':</span> [') : html.append('<span class="key collapse">'+ key +':</span> {');
_.each(_.keys(value), function(key, index) {
html.append(createBlock(key, value[key], id + "." + key));
});
_.isArray(value) ? html.append(']') : html.append('}');
} else {
html.append('<span class="key">'+ key +':</span> <span contenteditable="true" class="value" id=' + id + ' data-id=' + typeof value + '>'+ value +'</span>');
}
return html;
}
function getData(o, key) {
var ka = key.split('.');
for (var i = 0; i < ka.length; ++i) {
var n = ka[i];
if (n in o) {
o = o[n];
} else {
return;
}
}
return o;
}
function setData(o, key, value) {
var ka = key.split('.');
if (ka.length < 2) {
o[ka[0]] = value;
} else {
o = o[ka.shift()];
setData(o, ka.join("."), value);
}
}
.json-container {
/*outline: 1px solid #ccc;*/
font-family: monospace;
padding: 5px;
margin: 5px;
margin-top: 80px;
}
div > div {
padding-left: 20px;
}
.collapse {
cursor: pointer;
}
.key {
cursor: default;
color: red;
}
span[data-id=string] {
color: green;
}
span[data-id=number] {
color: darkorange;
}
span[data-id=boolean] {
color: blue;
}
span[data-id=object] {
color: magenta;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment