Javascript 如何以编程方式美化 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2614862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:09:30  来源:igfitidea点击:

How can I beautify JSON programmatically?

javascriptjsoncode-formattingpretty-print

提问by Randy Mayer

Do you know of any "JSON Beautifier" for JavaScript?

您知道 JavaScript 的任何“JSON Beautifier”吗?

From

{"name":"Steve","surname":"Jobs","company":"Apple"}

To

{
  "name" : "Steve",
  "surname" : "Jobs",
  "company" : "Apple"
}

Example

例子

some_magic(jsonObj); // return beautified JSON

回答by Andy E

Programmatic formatting solution:

程序化格式化解决方案:

The JSON.stringifymethod supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify许多现代浏览器(包括IE8)支持的方法可以输出一个美化的JSON字符串:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

此方法也包含在json2.js 中,用于支持旧浏览器。

Manual formatting solution

手动格式化解决方案

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

如果您不需要以编程方式执行此操作,请尝试JSON Lint。它不仅会美化您的 JSON,还会同时验证它。

回答by Shonzilla

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

对于更频繁地破解(缩小或混淆)JavaScript 的开发人员来说,这里有一些有趣的东西。

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

您可以在 5 分钟内构建自己的 CLI JavaScript 美化器,并在命令行中使用它。您将需要Mozilla Rhino、一些在线可用的 JS 美化器的 JavaScript 文件、小 hack 和一个脚本文件来包装它。

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

我写了一篇文章来解释这个过程:在 JavaScript 中实现的命令行 JavaScript 美化器