json - Prettify stringified object in javascript to serve in a static html page -
i'm trying use code prettify json object retrieved service , return in static page (has be).
the javascript functions work i'm having issues dealing stringified object.
it works fine encoding example before return statement html
json = "{\"a\":\"b\",\"c\":\"d\"}"
and not using stringify not using json.stringify real json object instead.
function getstaticresponse(jsonobjectretrieved){ return '<html>' + '<head>' + '<title>' + 'title' + '</title>' + '<link rel="stylesheet" type="text/css" href="' + '/something' + '">' + '</head>' + '<body>' + '<pre class="json-output box bg-color-weight-6 font-calibri">' + jsonformat(json.stringify(jsonobjectretrieved)) + '</pre>' + '</body>' + '</html>'; } 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>"'); };
many thanks
try removing call json.stringify
@ jsonformat(json.stringify(jsonobjectretrieved))
var json = "{\"a\":\"b\",\"c\":\"d\"}"; function getstaticresponse(title, jsonobjectretrieved) { return '<html>' + '<head>' + '<title>' + title + '</title>' + '<link rel="stylesheet" type="text/css" href="' + 123 + '">' + '</head>' + '<body>' + '<pre class="json-output box bg-color-weight-6 font-calibri">' + jsonformat(jsonobjectretrieved) + '</pre>' + '</body>' + '</html>'; } 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, null, 2) .replace(/\s"(\w*)":/g, ' "<span class="key">$1</span>":') .replace(/:\s"(.*)"/g, ': "<span class="string">$1</span>"'); }; document.write(getstaticresponse("abc", json));
Comments
Post a Comment