美化 javascript 中的字符串化对象以在静态 html 页面中提供服务

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

我正在尝试使用此代码美化从其他服务检索到的 JSON 对象,并 return 它在静态页面中(必须是)。

javascript 函数可以工作,但我在处理字符串化对象时遇到问题。

它可以很好地编码,例如在 html

的 return 语句之前
json = "{\"a\":\"b\",\"c\":\"d\"}"

并且不使用 stringify,但它不使用 JSON.stringify 和真正的 JSON 对象。

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"></span>":')
            .replace(/:\s"(.*)"/g, ': "<span class="string"></span>"');
};

非常感谢

尝试在 jsonFormat(JSON.stringify(jsonObjectRetrieved))

删除对 JSON.stringify 的调用

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"></span>":')
    .replace(/:\s"(.*)"/g, ': "<span class="string"></span>"');
};

document.write(getStaticResponse("abc", json));