我该如何以易于阅读(针对人类读者)的格式显示JSON? 我主要寻找缩进和空格,甚至可以使用颜色/字体样式等。
我该如何以易于阅读(针对人类读者)的格式显示JSON? 我主要寻找缩进和空格,甚至可以使用颜色/字体样式等。
在 JSON.stringify()
中,原生实现了漂亮打印。 第三个参数启用漂亮打印并设置间距:
var str = JSON.stringify(obj, null, 2); // spacing level = 2
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
在这里可以看到操作演示: jsfiddle
或者提供下面的完整代码段:
function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);
output(str);
output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
var json = syntaxHighlight(JSON.stringify(obj, undefined, 4));
var w = window.open();
var html = "";
html += "" + json + "
";
w.document.writeln(html);
- JayCrossler<pre>
标签。 - NoBugsstringify(...)
适用于 JSON 对象,而非 JSON 字符串。如果您有一个字符串需要先使用 JSON.parse(...)
进行解析。 - Vihung如果您有一个要漂亮打印的对象,那么用户Pumbaa80的回答非常好。如果您想要漂亮地打印有效的JSON 字符串,则需要先将其转换为对象:
var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);
这将从字符串构建一个JSON对象,然后使用JSON stringify的漂亮打印功能将其转换回字符串。
<pre></pre>
标签包裹起来。 - Undistraction<pre>RESULT</pre>
中,在HTML页面上也可以看到格式化的结果。 - Saghachivar jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07", "postalCode": "75007", "countryCode": "FRA", "countryLabel": "France" };
document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);
如果要在HTML中显示,您需要添加一个标签<pre></pre>
document.getElementById("result-after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, 2) +"</pre>"
例子:
var jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07", "postalCode": "75007", "countryCode": "FRA", "countryLabel": "France" };
document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);
document.getElementById("result-after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, 2) +"</pre>"
div { float:left; clear:both; margin: 1em 0; }
<div id="result-before"></div>
<div id="result-after"></div>
我想您需要的是这个:
JSON.stringify(obj, null, '\t');
JSON.stringify(obj, null, 2);
基于Pumbaa80的回答,我修改了代码以使用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, '%%');
console.dir()
,它是console.log(util.inspect())
的快捷方式。
(唯一的区别是它会跳过对象上定义的任何自定义inspect()
函数。)const object = JSON.parse(jsonString)
console.dir(object, {depth: null, colors: true})
使用命令行可以这样做:
cat package.json | node -e "process.stdin.pipe(new stream.Writable({write: chunk => console.dir(JSON.parse(chunk), {depth: null, colors: true})}))"
我使用 JSONView Chrome 扩展(它的界面非常漂亮):
编辑:添加了jsonreport.js
我还发布了一个独立的在线 JSON 格式化查看器 jsonreport.js,它提供了一个易于阅读的 HTML5 报告,您可以用来查看任何 JSON 数据。
您可以在 新 JavaScript HTML5 报告格式 中了解更多关于该格式的信息。
JSON.stringify(anObject, null, '\t');
来源:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
JSON.stringify() 方法将 JavaScript 值转换为一个 JSON 字符串。可选地,可以替换值,或者指定替换方式,或者仅包含某些属性。JSON.stringify({ x: 5, y: 6 });
// 输出:'{"x":5,"y":6}'
这是用户user123444555621的精彩HTML代码,适用于终端调试Node脚本:
function prettyJ(json) {
if (typeof json !== 'string') {
json = JSON.stringify(json, undefined, 2);
}
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function (match) {
let cls = "\x1b[36m";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "\x1b[34m";
} else {
cls = "\x1b[32m";
}
} else if (/true|false/.test(match)) {
cls = "\x1b[35m";
} else if (/null/.test(match)) {
cls = "\x1b[31m";
}
return cls + match + "\x1b[0m";
}
);
}
使用方法:
// thing = any json OR string of json
prettyJ(thing);
<pre>
标签将其包裹起来。 - Ryan WalkerJSON.stringify(data, null, 2)
格式化数据,然后使用 AceEditor、CodeMirror 或 Monaco Editor 进行显示。 - cwtuan