如何以编程方式美化JSON ?

你知道“JSON美容师”吗?JavaScript ?

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

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

例子

some_magic(jsonObj); // return beautified JSON
264873 次浏览

程序化格式化解决方案:

许多现代浏览器(包括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.

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.