如何以编程方式美化JSON? [英] How can I beautify JSON programmatically?

查看:194
本文介绍了如何以编程方式美化JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你知道JavaScript的JSON Beautifier吗?

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

来自

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

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

示例

some_magic(jsonObj); // return beautified JSON


推荐答案

程序化格式化解决方案:



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

Programmatic formatting solution:

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

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/

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

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

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

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆