在某些情况下,前端需要将后端接口返回的 JSON 数据进行高亮美化。现在市面上存在一些优秀的代码高亮工具,例如 highlight.jsprettify.js ,为了达到这种效果而引入整个插件,显得有些多余。下段代码简单实现了这个效果。

下面的方法接受一段需要美化的代码,方法为一些基本类型加上了类名,这样,我们就可以为代码添加样式。

function syntaxHighlight(json) {
  if (typeof json !== "string") {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
  return json.replace(
    /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
    function (match) {
      var cls = "number";
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = "key";
        } else {
          cls = "string";
        }
      } else if (/true|false/.test(match)) {
        cls = "boolean";
      } else if (/null/.test(match)) {
        cls = "null";
      }
      return '<span class="' + cls + '">' + match + "</span>";
    }
  );
}

例如后端返回的数据为

{
  "name": "Jons",
  "age": 14,
  "id": 001,
  "sex": "male",
  "address": null
}

经过我们高亮后的代码

../images/2022-03-09-json-highlight.jpeg