Javascript:如何直接从对象生成格式化的易于阅读的 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3515523/
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
Javascript: How to generate formatted easy-to-read JSON straight from an object?
提问by Ben Clayton
Possible Duplicate:
How can I beautify JSON programmatically?
可能的重复:
如何以编程方式美化 JSON?
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).
我知道如何使用 JSON.stringify 从对象生成 JSON,或者在我的情况下使用来自谷歌代码的方便的 jquery-json ( 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?
现在这工作正常,但输出对于人类来说很难阅读。有没有一种简单的方法/功能/任何方式来输出格式整齐的json文件?
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.
我想在不添加任何庞大的库的情况下理想地做到这一点 - 例如不是原型或 YUI 或其他任何东西。
回答by Cristian Sanchez
JSON.stringifytakes more optional arguments.
JSON.stringify需要更多的可选参数。
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.jsif you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>tag to get newlines to show.
应该在现代浏览器中工作,如果您需要不支持 JSON 辅助函数的浏览器的后备,它包含在json2.js 中。出于显示目的,将输出放在<pre>标签中以显示换行符。

