首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有句法色彩的Json漂亮印刷品

带有句法色彩的Json漂亮印刷品
EN

Stack Overflow用户
提问于 2018-09-12 08:21:04
回答 1查看 150关注 0票数 0

我试图用html打印我的json数据,并做一些语法着色。

但是我的代码中的空值(空列表、空字符串)有点问题。

这里是代码:

代码语言:javascript
复制
        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);
代码语言:javascript
复制
        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;
        }
代码语言:javascript
复制
<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变量有一个违章项的空列表值,然后这个键不是用正确的颜色打印的,它只是没有被处理。我试过不同的方法,但我不明白是怎么回事。

您可以尝试代码您的自我,并会注意到,语法颜色不工作,这最后一项。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-12 08:25:18

这也许能帮到你:

代码语言:javascript
复制
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));
代码语言:javascript
复制
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; }

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52290634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档