我如何以易于阅读(供人类阅读)的格式显示JSON?我主要寻找缩进和空白,甚至是颜色/字体样式等。
当前回答
出于调试目的,我使用:
console.debug("%o", data);
https://getfirebug.com/wiki/index.php/Console_APIhttps://developer.mozilla.org/en-US/docs/DOM/console
其他回答
非常感谢大家!根据前面的答案,这里是另一种提供自定义替换规则作为参数的变体方法:
renderJSON : function(json, rr, code, pre){
if (typeof json !== 'string') {
json = JSON.stringify(json, undefined, '\t');
}
var rules = {
def : 'color:black;',
defKey : function(match){
return '<strong>' + match + '</strong>';
},
types : [
{
name : 'True',
regex : /true/,
type : 'boolean',
style : 'color:lightgreen;'
},
{
name : 'False',
regex : /false/,
type : 'boolean',
style : 'color:lightred;'
},
{
name : 'Unicode',
regex : /"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?/,
type : 'string',
style : 'color:green;'
},
{
name : 'Null',
regex : /null/,
type : 'nil',
style : 'color:magenta;'
},
{
name : 'Number',
regex : /-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/,
type : 'number',
style : 'color:darkorange;'
},
{
name : 'Whitespace',
regex : /\s+/,
type : 'whitespace',
style : function(match){
return ' ';
}
}
],
keys : [
{
name : 'Testkey',
regex : /("testkey")/,
type : 'key',
style : function(match){
return '<h1>' + match + '</h1>';
}
}
],
punctuation : {
name : 'Punctuation',
regex : /([\,\.\}\{\[\]])/,
type : 'punctuation',
style : function(match){
return '<p>________</p>';
}
}
};
if('undefined' !== typeof jQuery){
rules = $.extend(rules, ('object' === typeof rr) ? rr : {});
}else{
for(var k in rr ){
rules[k] = rr[k];
}
}
var str = json.replace(/([\,\.\}\{\[\]]|"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var i = 0, p;
if (rules.punctuation.regex.test(match)) {
if('string' === typeof rules.punctuation.style){
return '<span style="'+ rules.punctuation.style + '">' + match + '</span>';
}else if('function' === typeof rules.punctuation.style){
return rules.punctuation.style(match);
} else{
return match;
}
}
if (/^"/.test(match)) {
if (/:$/.test(match)) {
for(i=0;i<rules.keys.length;i++){
p = rules.keys[i];
if (p.regex.test(match)) {
if('string' === typeof p.style){
return '<span style="'+ p.style + '">' + match + '</span>';
}else if('function' === typeof p.style){
return p.style(match);
} else{
return match;
}
}
}
return ('function'===typeof rules.defKey) ? rules.defKey(match) : '<span style="'+ rules.defKey + '">' + match + '</span>';
} else {
return ('function'===typeof rules.def) ? rules.def(match) : '<span style="'+ rules.def + '">' + match + '</span>';
}
} else {
for(i=0;i<rules.types.length;i++){
p = rules.types[i];
if (p.regex.test(match)) {
if('string' === typeof p.style){
return '<span style="'+ p.style + '">' + match + '</span>';
}else if('function' === typeof p.style){
return p.style(match);
} else{
return match;
}
}
}
}
});
if(true === pre)str = '<pre>' + str + '</pre>';
if(true === code)str = '<code>' + str + '</code>';
return str;
}
根据彭彭80的回答,我修改了代码,使用console.log颜色(当然是在Chrome上),而不是HTML。控制台内可以看到输出。您可以编辑函数内的_variables,添加更多样式。
function JSONstringify(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, '\t');
}
var
arr = [],
_string = 'color:green',
_number = 'color:darkorange',
_boolean = 'color:blue',
_null = 'color:magenta',
_key = 'color:red';
json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var style = _number;
if (/^"/.test(match)) {
if (/:$/.test(match)) {
style = _key;
} else {
style = _string;
}
} else if (/true|false/.test(match)) {
style = _boolean;
} else if (/null/.test(match)) {
style = _null;
}
arr.push(style);
arr.push('');
return '%c' + match + '%c';
});
arr.unshift(json);
console.log.apply(console, arr);
}
这里有一个书签,您可以使用:
javascript:function JSONstringify(json) {if (typeof json != 'string') {json = JSON.stringify(json, undefined, '\t');}var arr = [],_string = 'color:green',_number = 'color:darkorange',_boolean = 'color:blue',_null = 'color:magenta',_key = 'color:red';json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {var style = _number;if (/^"/.test(match)) {if (/:$/.test(match)) {style = _key;} else {style = _string;}} else if (/true|false/.test(match)) {style = _boolean;} else if (/null/.test(match)) {style = _null;}arr.push(style);arr.push('');return '%c' + match + '%c';});arr.unshift(json);console.log.apply(console, arr);};void(0);
用法:
var obj = {a:1, 'b':'foo', c:[false,null, {d:{e:1.3e5}}]};
JSONstringify(obj);
编辑:在变量声明之后,我试图用这一行转义%符号:
json = json.replace(/%/g, '%%');
但我发现Chrome不支持控制台中的%转义。奇怪的也许这在未来会奏效。
干杯
我想你在找这样的东西:
JSON.stringify(obj, null, '\t');
这“漂亮地打印”了JSON字符串,使用制表符进行缩进。
如果您喜欢使用空格而不是制表符,也可以使用数字表示您想要的空格数:
JSON.stringify(obj, null, 2);
如果您正在寻找一个漂亮的库来美化网页上的json。。。
Prism.js非常好。
http://prismjs.com/
我发现使用JSON.stringify(obj,undefined,2)获取缩进,然后使用prism添加主题是一个不错的方法。
如果通过ajax调用加载JSON,那么可以运行Prism的一个实用方法来美化
例如:
Prism.highlightAll()
这里有一些东西来修饰这个老掉牙但很好的问题。如果您想将格式化的对象转储到控制台,但它仍像一团包裹的乱麻一样转储,隐藏字符如下???
'{\n "_id": "630577bba145ff4f1",\n "role": "user"}'
但你想要这种可爱??:
{
"_id": "630557672d877bba145ff4f1",
"role": "user"
}
诀窍是将JSON.stringify()包装在console.log()语句中。如果你讨厌打字,尝试构建代码段来完成繁重的工作。。。
如果您正在处理大型对象,这非常有用。
在浏览器开发工具中的“代码段”部分添加一个代码段,如下所示(更多…):
let o = <object to print>
console.log(JSON.stringify(o, null, 4))
console.log(o)
然后简单地替换为对象(可以从当前上下文中获得)并运行代码段。
推荐文章
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 使用Jackson将JSON字符串转换为漂亮的打印JSON输出
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?