I need to prettify some JSON to display within an HTML <pre>
section.
The working javascript code I use is..
function transformJson(k, v) {
if (k === 'href' && typeof v === 'string') {
var label = v.replace(/&/gi, '&');
return '<a href=' + v + '>' + label + '</a>';
}
return v;
}
function jsonFormat(jsonString) {
var jsonObj = JSON.parse(jsonString, transformJson);
return JSON.stringify(jsonObj, undefined, 2)
.replace(/\s"(\w*)":/g, ' "<span class="key">$1</span>":')
.replace(/:\s"(.*)"/g, ': "<span class="string">$1</span>"');
};
Now I would like to make all attributes keys at the first level, regardless of the attribute value, links to "/documentation#attributeKeyText".
var jsonToPrettify = {
"href": "link/me",
"nonHrefButMakeThisKeyALink": "some_text",
"obj": {
"href": "link/me",
"thisKeyWontBeALinkInsteadBecauseHasAParent": "some_text"
}
}
console.log( jsonFormat( JSON.stringify( jsonToPrettify ) ) );
How can I achieve that? How can I check that the current attribute has no parent object?
Thanks
UPDATE:
Output of the current version is:
{
"<span class="key">href</span>": "<span class="string"><a href=link/me>link/me</a></span>",
"<span class="key">nonHrefButMakeThisKeyALink</span>": "<span class="string">some_text</span>",
"<span class="key">obj</span>": {
"<span class="key">href</span>": "<span class="string"><a href=link/me>link/me</a></span>",
"<span class="key">thisKeyWontBeALinkInsteadBecauseHasAParent</span>": "<span class="string">some_text</span>"
}
}
So I just want the span nonHrefButMakeThisKeyALink to be a link instead..