問題描述
可能重復:
如何以編程方式美化 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模板網!