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


当前回答

1行代码(无颜色)中的快速易读JSON输出:

document.documentElement.innerHTML='<pre>'+JSON.stringify(obj, null, 2)+'</pre>';

其他回答

您可以使用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})})”

我今天遇到了@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上的上下文代码

Douglas Crockford的JavaScript库中的JSON将通过stringify方法打印JSON。

您可能还发现这个老问题的答案很有用:如何在(unix)shell脚本中漂亮地打印JSON?

这里有一些东西来修饰这个老掉牙但很好的问题。如果您想将格式化的对象转储到控制台,但它仍像一团包裹的乱麻一样转储,隐藏字符如下???

'{\n    "_id": "630577bba145ff4f1",\n    "role": "user"}'

但你想要这种可爱??:

{
    "_id": "630557672d877bba145ff4f1",
    "role": "user"
}

诀窍是将JSON.stringify()包装在console.log()语句中。如果你讨厌打字,尝试构建代码段来完成繁重的工作。。。

如果您正在处理大型对象,这非常有用。

在浏览器开发工具中的“代码段”部分添加一个代码段,如下所示(更多…):

let o = <object to print>
console.log(JSON.stringify(o, null, 4))
console.log(o)

然后简单地替换为对象(可以从当前上下文中获得)并运行代码段。

这很好:

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