在html展示JSON

作者: 5df463a52098 | 来源:发表于2018-05-28 13:28 被阅读18次

方式一:以默认黑体显示Json字符串。

html部分:

<pre id="results"></pre>

js部分:

var data = {
                    'method': 'seal.query',
                    'requestId': '9yyh888c8',
                    'code': 0,                  // 详见操作码列表
                    'data': [
                        {
                            'sealName': '测试章1',
                            'queryTime': '2020-05-05 00:00:01',
                            'sealStatus': '1'
                        }
                    ],
                    'message': '调用查询接口成功!'
                }
$("#results").html(JSON.stringify(data, null, 2))

方式二:以彩色显示Json字符串。

html部分:

<pre id="results"></pre>

css部分:

 <style>
 pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
 .string { color: green; }
.number { color: darkorange; }
 .boolean { color: blue; }
 .null { color: magenta; }
 .key { color: red; }
 </style>

js部分:

<script type="text/javascript">
 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>';
 });
}

$('#results').html(syntaxHighlight(data));
</script>

相关文章

网友评论

    本文标题:在html展示JSON

    本文链接:https://www.haomeiwen.com/subject/soxgjftx.html