如何在客户端的 HTML 页面中语法高亮 JSON?

JJD*_*JJD 1 browser json greasemonkey syntax-highlighting userscripts

我正在使用外部服务的 HTML 文档页面,该服务在 HTML 页面中呈现 JSON 片段。HTML 源代码如下所示:

<pre>{
    "product-link": "https://example.com/product-link",
    "teaser_image": "https://example.com/teaser-image",
    "product_image_first": "https://example.com/product-image-first",
    "headline": "Example headline",
}</pre>
Run Code Online (Sandbox Code Playgroud)

JSON 块在没有语法突出显示的情况下呈现。由于我无法控制外部服务,因此我想通过用户脚本将语法突出显示(颜色)应用于 JSON 片段。

我找到了Greasemonkey,但仍然没有了解如何注入语法高亮库。

JJD*_*JJD 5

感谢xander,这是我基于代码美化的用户脚本的第一个工作版本:

(function(d) {

  stylizePreElements = function() {
    var preElements = document.getElementsByTagName("pre");
    for (i = 0; i < preElements.length; ++i) {
      var preElement = preElements[i];
      preElement.className += "prettyprint";
    }
  };

  injectPrettifyScript = function() {
    var scriptElement = document.createElement('script');
    scriptElement.setAttribute("src", "https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js");
    document.head.appendChild(scriptElement);
  };

  stylizePreElements();
  injectPrettifyScript();

})(document)
Run Code Online (Sandbox Code Playgroud)

谢谢你让我的日子更美好!