在 JavaScript 中美化 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11359291/
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
Prettify JSON Array in JavaScript
提问by Ryan Brodie
Possible Duplicate:
JSON pretty print using JavaScript
I'm working on a project that will be used to help analyse and understand JSON arrays by future developers of a platform. I'm referencing Facebook's brilliant Graph Explorer page, seen here, and want to output our array in a prettified, correctly tab indented and line breaker array, just as it does on the explorer.
我正在从事一个项目,该项目将用于帮助平台的未来开发人员分析和理解 JSON 数组。我正在引用 Facebook 出色的 Graph Explorer 页面,见这里,并希望以美化的、正确的制表符缩进和换行符数组输出我们的数组,就像它在资源管理器上所做的那样。
The arrays are outputted to a textarea
, and because of this I think I'm running into issues with the line breaking and tabbing. I've also tried using the prettify library, but with no luck.
数组输出到 a textarea
,因此我想我遇到了换行和制表符的问题。我也试过使用美化库,但没有运气。
Example:
例子:
{"outcome" : "success", "result" : {"name" : "messaging-sockets", "default-interface" : "external", "include" : [], "socket-binding" : {"messaging" : {"name" : "messaging", "interface" : null, "port" : 5445, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}, "messaging-throughput" : {"name" : "messaging-throughput", "interface" : null, "port" : 5455, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}}}, "compensating-operation" : null}
To:
到:
{
"outcome":"success",
"result":{
"name":"messaging-sockets",
"default-interface":"external",
"include":[
],
"socket-binding":{
"messaging":{
"name":"messaging",
"interface":null,
"port":5445,
"fixed-port":null,
"multicast-address":null,
"multicast-port":null
},
"messaging-throughput":{
"name":"messaging-throughput",
"interface":null,
"port":5455,
"fixed-port":null,
"multicast-address":null,
"multicast-port":null
}
}
},
"compensating-operation":null
}
回答by Engineer
You may use JSON.stringify:
您可以使用JSON.stringify:
JSON.stringify(jsonobj,null,'\t')
See the demo.
请参阅演示。
UPDATE:If you don't have jsonobj
,but have json string,then before using stringify
function,convert json string to json object by this line:
更新:如果你没有jsonobj
,但有 json 字符串,那么在使用stringify
函数之前,通过这一行将 json 字符串转换为 json 对象:
jsonobj = JSON.parse(jsonstring);