可能重复:
如何以编程方式美化 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
Browserify,Babel 6,Gulp - 传播运算符上的意外令牌Browserify, Babel 6, Gulp - Unexpected token on spread operator(Browserify,Babel 6,Gulp - 传播运算符上的意外令牌)
是否可以将标志传递给 Gulp 以使其以不同的方式Is it possible to pass a flag to Gulp to have it run tasks in different ways?(是否可以将标志传递给 Gulp 以使其以不同的方式运行任务
为什么我们需要在全局和本地安装 gulp?Why do we need to install gulp globally and locally?(为什么我们需要在全局和本地安装 gulp?)
如何一个接一个地依次运行 Gulp 任务How to run Gulp tasks sequentially one after the other(如何一个接一个地依次运行 Gulp 任务)
打开 Javascript 文件时 Visual Studio 2015 崩溃Visual Studio 2015 crashes when opening Javascript files(打开 Javascript 文件时 Visual Studio 2015 崩溃)
检测 FLASH 插件崩溃Detect FLASH plugin crashes(检测 FLASH 插件崩溃)