javascript - 带有句法着色的 Json Pretty Print

标签 javascript jquery html json

我正在尝试在 html 中漂亮地打印我的 json 数据,并进行一些语法着色。

但是我在代码中遇到了一些空值(空列表、空字符串)的问题。

这是代码:

        if (!library)
          var library = {};

        function isInt(value) {
            return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
        };
        library.json = {
          replacer: function(match, pIndent, pKey, pVal, pEnd) {
            var int = '<span class=json-int>';
            var key = '<span class=json-key>';
            var val = '<span class=json-value>';
            var str = '<span class=json-string>';
            var r = pIndent || '';
            if (pKey)
              r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
            if (pVal)
              //r = r + (pVal[0] == '"'i ? str : val) + pVal + '</span>';
              r = r + (isInt(pVal) ? int : str) + pVal + '</span>';
            return r + (pEnd || '');
          },
          prettyPrint: function(obj) {
            var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
            return JSON.stringify(obj, null, 3)
              .replace(/&/g, '&amp;').replace(/\\"/g, '&quot;')
              .replace(/</g, '&lt;').replace(/>/g, '&gt;')
              .replace(jsonLine, library.json.replacer);
          }
        };
        var lint = {
                "LintResult": "FAILED",
                "CFN_NAG": [
                    {
                        "filename": "sam.yaml",
                        "file_results": {
                            "failure_count": 0,
                            "violations": []
                        }
                    }
                ],
              "Comment": "If above CFN_NAG key has None value, check code execution log for errors/exceptions"
        }
        $('#lint').html(library.json.prettyPrint(lint));
        //document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
        pre {
          background-color: ghostwhite;
          bovrder: 1px solid silver;
          padding: 10px 20px;
          margin: 20px; 
        }
        .json-key {
          color: brown;
        }
        .json-value {
          color: navy;
        }
        .json-string {
          color: olive;
        }
        .json-int {
          color: fuchsia;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="background-color:lightblue">  
  <h1>JSON Data:</h1>
  <pre id="lint"></pre>
    
</div>
<p>A JSON string with 12 spaces per indentation.</p>

在上面的代码中,lint json变量的violations项有一个空列表值,然后这个键没有以正确的颜色打印,它只是未处理。 我尝试了不同的方法,但我不明白出了什么问题。

您可以自己尝试该代码,您会发现语法着色不适用于最后一项。

最佳答案

这可能会帮助你:

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    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>';
    });
}

var obj = {
            "LintResult": "FAILED",
            "CFN_NAG": [
                {
                    "filename": "sam.yaml",
                    "file_results": {
                        "failure_count": 0,
                        "violations": []
                    }
                }
            ],
          "Comment": "If above CFN_NAG key has None value, check code execution log for errors/exceptions"
    };
var str = JSON.stringify(obj, undefined, 4);

output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; background: ghostwhite }
.string { color: olive; }
.number { color: fuchsia; }
.boolean { color: navy; }
.null { color: magenta; }
.key { color: brown; }

关于javascript - 带有句法着色的 Json Pretty Print,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52290634/

相关文章:

javascript - Nodejs res.render函数不更新html页面

javascript - 从外部服务器读取使用脚本 src 标记调用的文件的响应

jquery - Firefox 和 Chrome CSS 绝对定位问题

javascript - 按比例缩小的 div 会占据整个空间,您可以滚动浏览空白空间

Sprite 导航图像的 HTML 和 CSS 标记

javascript - 在 Angular.js 中连接模型

javascript - 使窗口在 Chrome 中不可调整大小

javascript - 如何在 Gmail API 中获取内部日期?

jquery - 如何将 fancybox 放置在顶部

html - 具有第二个 ID 变量作为列拆分的数据框的 R 导出表