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

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

问题描述

可能重复:
如何以编程方式美化 JSON?

我知道如何使用 JSON.stringify 从对象生成 JSON,或者在我的例子中,来自谷歌代码的方便 jquery-json (https://github.com/krinkle/jquery-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 文件?

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.stringify({a: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]
 }
}

例如添加了换行符和标签.较大的文档更容易阅读.

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

我希望在不添加任何大型库的情况下理想地做到这一点 - 例如.不是原型或 YUI 或其他任何东西.

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

推荐答案

JSON.stringify 需要更多 可选参数.

试试:

 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

发件人:

如何以编程方式美化 JSON?

应该在现代浏览器中工作,如果您需要,它包含在 json2.js 中不支持 JSON 辅助函数的浏览器的后备.出于显示目的,将输出放在 <pre> 标记中以显示换行符.

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. For display purposes, put the output in a <pre> tag to get newlines to show.

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

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