Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

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

Possible Duplicate:

(可能重复:)

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,或者在我的情况下从google代码( https://github.com/krinkle/jquery-json )生成方便的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]
 }
}

Eg 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 - eg not prototype or YUI or whatever.

(我想在没有添加任何大型库的情况下理想地执行此操作 - 例如,不是原型或YUI或其他任何东西。)

  ask by Ben Clayton translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JSON.stringify takes 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, ""); // Indented with tab

From:

(从:)

How can I beautify JSON programmatically?

(如何以编程方式美化JSON?)

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.

(应该在现代浏览器中工作,并且如果您需要对不支持JSON帮助程序函数的浏览器进行回退,它将包含在json2.js中 。)

For display purposes, put the output in a <pre> tag to get newlines to show.

(出于显示目的,将输出放在<pre>标记中以获取要显示的换行符。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...