我如何以易于阅读(供人类阅读)的格式显示JSON?我主要寻找缩进和空白,甚至是颜色/字体样式等。


当前回答

用户Pumbaa80的答案很好,如果你有一个想要漂亮打印的对象。如果要从一个有效的JSON字符串开始打印,需要首先将其转换为一个对象:

var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);  

这将从字符串构建一个JSON对象,然后使用JSON字符串的漂亮打印将其转换回字符串。

其他回答

这很好:

https://github.com/mafintosh/json-markup来自马芬托什

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

您可以使用console.dir(),这是console.log(util.inspect())的快捷方式。(唯一的区别是它忽略了在对象上定义的任何自定义inspect()函数。)

它使用语法高亮显示、智能缩进、从键中删除引号,并使输出尽可能漂亮。

const object = JSON.parse(jsonString)

console.dir(object, {depth: null, colors: true})

对于命令行:

cat package.json | node-e“process.stdin.pipe(newstream.Writeable({write:cchunk=>console.dir(json.parse(chunk),{depth:null,colors:true})})”

这是user123444555621的很棒的HTML,适合终端。易于调试节点脚本:

function prettyJ(json) {
  if (typeof json !== 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  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 = "\x1b[36m";
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = "\x1b[34m";
        } else {
          cls = "\x1b[32m";
        }
      } else if (/true|false/.test(match)) {
        cls = "\x1b[35m"; 
      } else if (/null/.test(match)) {
        cls = "\x1b[31m";
      }
      return cls + match + "\x1b[0m";
    }
  );
}

用法:

// thing = any json OR string of json
prettyJ(thing);

漂亮的打印是在JSON.stringify()中本地实现的。第三个参数启用漂亮的打印并设置要使用的间距:

var str = JSON.stringify(obj, null, 2); // spacing level = 2

如果您需要语法高亮显示,可以使用一些正则表达式魔法,例如:

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    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>';
    });
}

在这里查看实际操作:jsfiddle

或以下提供的完整片段:

函数输出(inp){document.body.appendChild(document.createElement('pre')).innerHTML=inp;}函数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,函数(匹配){var cls=“数字”;if(/^“/.test(匹配)){if(/:$/.test(匹配)){cls=“键”;}其他{cls=“字符串”;}}else if(/true|false/.test(匹配)){cls=“布尔值”;}else if(/null/.test(match)){cls=“null”;}return'<span class=“'+cls+'”>'+match+'</span>';});}var obj={a:1,'b':'o',c:[false,'false',null,'null',{d:{e:1.3e5,f:'1.3e5'}}]};var str=JSON.stringify(obj,未定义,4);输出(str);输出(syntaxHighlight(str));前置{outline:1px实心#ccc;padding:5px;margin:5px;}.string{color:绿色;}.number{color:深橙色;}布尔{color:blue;}.null{color:洋红色;}.key{color:红色;}

var jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07",  "postalCode": "75007", "countryCode": "FRA",  "countryLabel": "France" };

document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);

如果以HTML显示,则应添加应答器<pre></pre>

document.getElementById("result-after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, 2) +"</pre>"

例子:

var jsonObj={“streetLabel”:“Avenue Anatole France”,“city”:“Paris 07”,“postalCode”:“75007”;document.getElementById(“result before”).innerHTML=JSON.stringfy(jsonObj);document.getElementById(“resultafter”).innerHTML=“<pre>”+JSON.stringify(jsonObj,未定义,2)+“</pre>”div{float:left;clear:both;margin:1em 0;}<div id=“result before”></div><div id=“result after”></div>