Javascript:如何直接从对象生成格式化的易于阅读的JSON? [英] Javascript: How to generate formatted easy-to-read JSON straight from an object?

查看:200
本文介绍了Javascript:如何直接从对象生成格式化的易于阅读的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

知道如何使用JSON.stringify从一个对象生成JSON,或者在我的情况下从谷歌代码( https://github.com/krinkle/jquery-json )。

现在这个工作正常,但输出很难读取人类。有没有一个简单的方法/函数/无论输出一个整齐格式化的JSON文件?

这就是我的意思:

  JSON.stringify({一个:1,b:2,C:{d:1,E:[1,2]}}); 

给出..

 {a:1,b:2,c:{d:1,e:[1,2]}}

我想要这样的代码:

 < 
a:1,
b:2,
c:{
d:1,
e:[1,2]
}
}

添加了新行和标签。阅读更大的文档要容易得多。



我希望在不添加任何大型库的情况下完成此操作。不是原型或YUI或其他。

解决方案

JSON.stringify 需要更多可选参数



试试:

  JSON.stringify({a:1,b:2,c:{d: 1,e:[1,2]}},null,4); //缩进4个空格
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}},null,\t); //缩进tab

From:

如何以编程方式美化JSON



在现代浏览器中工作,如果您需要对浏览器进行回退,则它包含在 json2.js 中不支持JSON帮助函数。


Possible Duplicate:
How can I beautify JSON programmatically?

I know how to generate JSON from an object using JSON.stringify, or in my case the handy jquery-json from google code (https://github.com/krinkle/jquery-json).

Now this works fine, but the output is hard to read for humans. Is there an easy way / function / whatever to output a neatly formatted json file?

This is what I mean:

JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}); 

gives..

"{"a":1,"b":2,"c":{"d":1,"e":[1,2]}}"

I'd like something like this instead:

{
 "a":1,
 "b":2,
 "c":{
    "d":1,
    "e":[1,2]
 }
}

E.g. with newlines and tabs added. It's much easier to read for larger documents.

I'd like to do this ideally without adding any huge libraries - e.g. not prototype or YUI or whatever.

解决方案

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions.

这篇关于Javascript:如何直接从对象生成格式化的易于阅读的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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