使用JavaScript美化打印JSON

3379

我该如何以易于阅读(针对人类读者)的格式显示JSON? 我主要寻找缩进和空格,甚至可以使用颜色/字体样式等。


23
如果你只是将内容输出到HTML,可以用<pre>标签将其包裹起来。 - Ryan Walker
所有答案都可以,但你必须在HTML中使用JavaScript的 var str = JSON.stringify(obj, null, 2); // <pre id="output_result_div"></pre> 来输出结果。 - pankaj
使用 Monaco Editor 在 2023 年展示您的 JSON 是更好的选择。 - cwtuan
使用 JSON.stringify(data, null, 2) 格式化数据,然后使用 AceEditorCodeMirrorMonaco Editor 进行显示。 - cwtuan
32个回答

5

无法找到控制台语法高亮显示的好解决方案,所以这是我的建议。

安装和添加cli-highlight依赖项

npm install cli-highlight --save

全局定义logjson

const highlight = require('cli-highlight').highlight
console.logjson = (obj) => console.log(
                               highlight( JSON.stringify(obj, null, 4), 
                                          { language: 'json', ignoreIllegals: true } ));

使用

console.logjson({foo: "bar", someArray: ["string1", "string2"]});

output


4

4
今天我遇到了@Pumbaa80的代码问题。我正在尝试将JSON语法高亮应用于在Mithril视图中呈现的数据,因此我需要为JSON.stringify输出中的每个内容创建DOM节点。
我还将非常长的正则表达式拆分成其组成部分。
render_json = (data) ->
  # wraps JSON data in span elements so that syntax highlighting may be
  # applied. Should be placed in a `whitespace: pre` context
  if typeof(data) isnt 'string'
    data = JSON.stringify(data, undefined, 2)
  unicode =     /"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?/
  keyword =     /\b(true|false|null)\b/
  whitespace =  /\s+/
  punctuation = /[,.}{\[\]]/
  number =      /-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/

  syntax = '(' + [unicode, keyword, whitespace,
            punctuation, number].map((r) -> r.source).join('|') + ')'
  parser = new RegExp(syntax, 'g')

  nodes = data.match(parser) ? []
  select_class = (node) ->
    if punctuation.test(node)
      return 'punctuation'
    if /^\s+$/.test(node)
      return 'whitespace'
    if /^\"/.test(node)
      if /:$/.test(node)
        return 'key'
      return 'string'

    if /true|false/.test(node)
      return 'boolean'

     if /null/.test(node)
       return 'null'
     return 'number'
  return nodes.map (node) ->
    cls = select_class(node)
    return Mithril('span', {class: cls}, node)

在 Github 上的上下文代码 这里

4
如果您需要在文本区域中运行此操作,接受的解决方案将无法正常工作。

$("#textarea").append(formatJSON(JSON.stringify(jsonobject),true));
function formatJSON(json,textarea) {
    var nl;
    if(textarea) {
        nl = "&#13;&#10;";
    } else {
        nl = "<br>";
    }
    var tab = "&#160;&#160;&#160;&#160;";
    var ret = "";
    var numquotes = 0;
    var betweenquotes = false;
    var firstquote = false;
    for (var i = 0; i < json.length; i++) {
        var c = json[i];
        if(c == '"') {
            numquotes ++;
            if((numquotes + 2) % 2 == 1) {
                betweenquotes = true;
            } else {
                betweenquotes = false;
            }
            if((numquotes + 3) % 4 == 0) {
                firstquote = true;
            } else {
                firstquote = false;
            }
        }

        if(c == '[' && !betweenquotes) {
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '{' && !betweenquotes) {
            ret += tab;
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '"' && firstquote) {
            ret += tab + tab;
            ret += c;
            continue;
        } else if (c == '"' && !firstquote) {
            ret += c;
            continue;
        }
        if(c == ',' && !betweenquotes) {
            ret += c;
            ret += nl;
            continue;
        }
        if(c == '}' && !betweenquotes) {
            ret += nl;
            ret += tab;
            ret += c;
            continue;
        }
        if(c == ']' && !betweenquotes) {
            ret += nl;
            ret += c;
            continue;
        }
        ret += c;
    } // i loop
    return ret;
}

2

这很好:

https://github.com/mafintosh/json-markup 来自 mafintosh

const jsonMarkup = require('json-markup')
const html = jsonMarkup({hello:'world'})
document.querySelector('#myElem').innerHTML = html

HTML

<link ref="stylesheet" href="style.css">
<div id="myElem></div>

这里可以找到示例样式表

https://raw.githubusercontent.com/mafintosh/json-markup/master/style.css

2

使用 BootstrapHTML 中突出显示并美化它:

function prettifyJson(json, prettify) {
    if (typeof json !== 'string') {
        if (prettify) {
            json = JSON.stringify(json, undefined, 4);
        } else {
            json = JSON.stringify(json);
        }
    }
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
        function(match) {
            let cls = "<span>";
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = "<span class='text-danger'>";
                } else {
                    cls = "<span>";
                }
            } else if (/true|false/.test(match)) {
                cls = "<span class='text-primary'>";
            } else if (/null/.test(match)) {
                cls = "<span class='text-info'>";
            }
            return cls + match + "</span>";
        }
    );
}

1
基于@user123444555621的基础上,稍微现代化了一些。
const clsMap = [
    [/^".*:$/, "key"],
    [/^"/, "string"],
    [/true|false/, "boolean"],
    [/null/, "key"],
    [/.*/, "number"],
]

const syntaxHighlight = obj => JSON.stringify(obj, null, 4)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, match => `<span class="${clsMap.find(([regex]) => regex.test(match))[1]}">${match}</span>`);

您也可以在 JavaScript 中指定颜色(无需使用 CSS)。

const clsMap = [
    [/^".*:$/, "red"],
    [/^"/, "green"],
    [/true|false/, "blue"],
    [/null/, "magenta"],
    [/.*/, "darkorange"],
]

const syntaxHighlight = obj => JSON.stringify(obj, null, 4)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, match => `<span style="color:${clsMap.find(([regex]) => regex.test(match))[1]}">${match}</span>`);

还有一个使用更少正则表达式的版本。

const clsMap = [
    [match => match.startsWith('"') && match.endsWith(':'), "red"],
    [match => match.startsWith('"'), "green"],
    [match => match === "true" || match === "false" , "blue"],
    [match => match === "null", "magenta"],
    [() => true, "darkorange"],
];
    
const syntaxHighlight = obj => JSON.stringify(obj, null, 4)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, match => `<span style="color:${clsMap.find(([fn]) => fn(match))[1]}">${match}</span>`);

1

这是关于 Laravel 和 Codeigniter 的内容。

控制器:可以像下面这样从控制器返回 JSON 值:

return json_encode($data, JSON_PRETTY_PRINT);

在脚本中:

<script> $('.jsonPre').html(result); </script>

结果将会是:

result will be


1
<!-- here is a complete example pretty print with more space between lines-->
<!-- be sure to pass a json string not a json object -->
<!-- use line-height to increase or decrease spacing between json lines -->

<style  type="text/css">
.preJsonTxt{
  font-size: 18px;
  text-overflow: ellipsis;
  overflow: hidden;
  line-height: 200%;
}
.boxedIn{
  border: 1px solid black;
  margin: 20px;
  padding: 20px;
}
</style>

<div class="boxedIn">
    <h3>Configuration Parameters</h3>
    <pre id="jsonCfgParams" class="preJsonTxt">{{ cfgParams }}</pre>
</div>

<script language="JavaScript">
$( document ).ready(function()
{
     $(formatJson);

     <!-- this will do a pretty print on the json cfg params      -->
     function formatJson() {
         var element = $("#jsonCfgParams");
         var obj = JSON.parse(element.text());
        element.html(JSON.stringify(obj, undefined, 2));
     }
});
</script>

0

以下是如何在不使用本地函数的情况下打印的方法。

function pretty(ob, lvl = 0) {

  let temp = [];

  if(typeof ob === "object"){
    for(let x in ob) {
      if(ob.hasOwnProperty(x)) {
        temp.push( getTabs(lvl+1) + x + ":" + pretty(ob[x], lvl+1) );
      }
    }
    return "{\n"+ temp.join(",\n") +"\n" + getTabs(lvl) + "}";
  }
  else {
    return ob;
  }

}

function getTabs(n) {
  let c = 0, res = "";
  while(c++ < n)
    res+="\t";
  return res;
}

let obj = {a: {b: 2}, x: {y: 3}};
console.log(pretty(obj));

/*
  {
    a: {
      b: 2
    },
    x: {
      y: 3
    }
  }
*/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接