使用JavaScript打印漂亮的JSON

JavaScript

十三西里GO

2020-03-09

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

第191篇《使用JavaScript打印漂亮的JSON》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

12个回答
卡卡西Near 2020.03.09
<!-- 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>
Tom伽罗 2020.03.09

我建议使用HighlightJS它使用接受答案相同的原理,但也适用于许多其他语言,并具有许多预定义的配色方案如果使用RequireJS,则可以使用以下命令生成兼容模块

python3 tools/build.py -tamd json xml <specify other language here>

生成依赖于Python3和Java。添加-n以生成非缩小版本。

null 2020.03.09

这是不使用本机功能即可进行打印的方法。

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
    }
  }
*/
GO小胖 2020.03.09

如果您正在寻找一个漂亮的库来美化网页上的json ...

Prism.js相当不错。

http://prismjs.com/

我发现使用JSON.stringify(obj,undefined,2)来获得缩进,然后使用棱镜来添加主题是一种很好的方法。

如果要通过ajax调用加载JSON,则可以运行Prism的一种实用程序方法来美化

例如:

Prism.highlightAll()
斯丁猿 2020.03.09

这是用React编写的一个简单的JSON格式/颜色组件:

const HighlightedJSON = ({ json }: Object) => {
  const highlightedJSON = jsonObj =>
    Object.keys(jsonObj).map(key => {
      const value = jsonObj[key];
      let valueType = typeof value;
      const isSimpleValue =
        ["string", "number", "boolean"].includes(valueType) || !value;
      if (isSimpleValue && valueType === "object") {
        valueType = "null";
      }
      return (
        <div key={key} className="line">
          <span className="key">{key}:</span>
          {isSimpleValue ? (
            <span className={valueType}>{`${value}`}</span>
          ) : (
            highlightedJSON(value)
          )}
        </div>
      );
    });
  return <div className="json">{highlightedJSON(json)}</div>;
};

看到它在此CodePen中工作:https ://codepen.io/benshope/pen/BxVpjo

希望有帮助!

老丝村村 2020.03.09

您可以使用JSON.stringify(your object, null, 2) 第二个参数用作替换函数,该函数使用key和Val作为参数。如果要在JSON对象中进行修改,可以使用第二个参数。

更多参考:https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

飞云前端西门 2020.03.09

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

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

神无伽罗阳光 2020.03.09

效果很好:

console.table()

在此处阅读更多信息:https : //developer.mozilla.org/pt-BR/docs/Web/API/Console/table

小哥前端 2020.03.09

出于调试目的,我使用:

console.debug(“%o”,data);
伽罗Mandy 2020.03.09

您可以使用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(new stream.Writable({write: chunk => console.dir(JSON.parse(chunk), {depth: null, colors: true})}))"

米亚小小神乐 2020.03.09

我使用JSONView Chrome扩展程序(它看起来很漂亮:):

编辑:添加 jsonreport.js

我还发布了一个在线的独立JSON漂亮打印查看器jsonreport.js,该查看器提供了人类可读的HTML5报告,可用于查看任何JSON数据。

您可以在“ 新JavaScript HTML5报告格式”中阅读有关该格式的更多信息

达蒙阳光乐 2020.03.09
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", "countryCode": "FRA",  "countryLabel": "France" };

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

document.getElementById("result-after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, 2) +"</pre>"
div { float:left; clear:both; margin: 1em 0; }
<div id="result-before"></div>
<div id="result-after"></div>

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android