本文翻译自:How can I beautify JSON programmatically? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- How can I pretty-print JSON using JavaScript? 如何使用JavaScript漂亮地打印JSON? 24 answers 24个答案
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
#1楼
参考:https://stackoom.com/question/AyFC/如何以编程方式美化JSON-重复
#2楼
Programmatic formatting solution: 编程格式化解决方案:
The JSON.stringify
method supported by many modern browsers (including IE8) can output a beautified JSON string: 许多现代浏览器(包括IE8)支持的JSON.stringify
方法可以输出一个美化的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 . 如果您不需要以编程方式执行此操作,请尝试JSON Lint 。 Not only will it prettify your JSON, it will validate it at the same time. 它不仅会美化你的JSON,它还会同时验证它。
#3楼
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. 您可以在5分钟内构建自己的CLI JavaScript美化器,并在命令行中使用它。 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. 你需要Mozilla Rhino ,一些在线可用的JS美化器的JavaScript文件,小黑客和一个脚本文件来包装它。
I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript . 我写了一篇文章解释了这个过程: 用JavaScript实现的命令行JavaScript美化 。