Prettify stringified object in javascript to serve in a static html page

时间:2016-02-03 02:52:37

标签: javascript json stringify

I'm trying to use this code to prettify a JSON object retrieved from another service and return it in a static page (has to be).

The javascript functions work but I'm having issues dealing with the stringified object.

It works fine encoding for example before the return statement for the html

json = "{\"a\":\"b\",\"c\":\"d\"}"

and not using stringify but it does not using JSON.stringify with a 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, '&amp;');
    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

1 个答案:

答案 0 :(得分:1)

Try removing call to JSON.stringify at 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, '&amp;');
    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));