使用JavaScript打印JSON
如何以易于阅读(对于人类读者)的格式显示JSON?我主要寻找缩进和空白,甚至可能还有颜色/字体样式/等等。我使用(它非常漂亮:): 编辑:添加了使用JavaScript打印JSON,javascript,json,pretty-print,Javascript,Json,Pretty Print,如何以易于阅读(对于人类读者)的格式显示JSON?我主要寻找缩进和空白,甚至可能还有颜色/字体样式/等等。我使用(它非常漂亮:): 编辑:添加了jsonreport.js 我还发布了一个在线独立的JSON漂亮打印查看器jsonreport.js,它提供了一个可读的HTML5报告,可以用来查看任何JSON数据 您可以在中阅读有关格式的更多信息。Douglas Crockford在JavaScript库中的JSON将通过stringify方法打印JSON 您可能还会发现这个老问题的答案很有用:。第三
jsonreport.js
我还发布了一个在线独立的JSON漂亮打印查看器jsonreport.js,它提供了一个可读的HTML5报告,可以用来查看任何JSON数据
您可以在中阅读有关格式的更多信息。Douglas Crockford在JavaScript库中的JSON将通过stringify方法打印JSON 您可能还会发现这个老问题的答案很有用:。第三个参数启用漂亮打印并设置要使用的间距:
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>';
});
}
出于调试目的,我使用: console.debug("%o", data); 调试(“%o”,数据);
var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);
这将从字符串中构建一个JSON对象,然后使用JSON stringify的漂亮打印将其转换回字符串。根据Pumbaa80的回答,我修改了代码以使用console.log颜色(当然是在Chrome上),而不是HTML。可以在控制台内部看到输出。您可以编辑函数中的_变量,添加更多样式
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);
function prettifyJson(json, prettify) {
if (typeof json !== 'string') {
if (prettify) {
json = JSON.stringify(json, undefined, 4);
} else {
json = JSON.stringify(json);
}
}
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 = "<span>";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "<span class='text-danger'>";
} else {
cls = "<span>";
}
} else if (/true|false/.test(match)) {
cls = "<span class='text-primary'>";
} else if (/null/.test(match)) {
cls = "<span class='text-info'>";
}
return cls + match + "</span>";
}
);
}
编辑:我只是尝试在变量声明之后用此行转义%符号:
json = json.replace(/%/g, '%%');
但我发现Chrome不支持控制台中的%转义。奇怪。。。也许这在将来会起作用
干杯
我今天遇到了@Pumbaa80代码的问题。我试图将JSON语法高亮显示应用到视图中呈现的数据,因此我需要为
JSON.stringify
输出中的所有内容创建DOM节点
我也将很长的正则表达式拆分为它的组成部分
render_json=(数据)->
#将JSON数据包装到span元素中,以便可以突出显示语法
#应用。应置于`空白:pre`上下文中
如果(数据)的类型不是“字符串”
data=JSON.stringify(数据,未定义,2)
unicode=/“(\\u[a-zA-Z0-9]{4}\\[^u]\\[^\\\”])*”(\s*:)/
关键字=/\b(真|假|空)\b/
空白=/\s+/
标点符号=/[,.}{\[\]]/
数字=/-?\d+(?:\。\d*)?(?:[eE][+\-]?\d+/
语法='('+[unicode,关键字,空格,
标点符号,数字].map((r)->r.source.join(“|”)+”)
parser=newregexp(语法“g”)
节点=数据。匹配(解析器)?[]
选择_class=(节点)->
if标点。测试(节点)
返回“标点符号”
if/^\s+$/.test(节点)
返回“空白”
if/^\“/.test(节点)
if/:$/.test(节点)
返回“键”
返回“字符串”
if/true | false/.test(节点)
返回“boolean”
if/null/.test(节点)
返回“null”
返回“编号”
return nodes.map(节点)->
cls=选择类(节点)
返回Mithril('span',{class:cls},node)
Github上的上下文代码对于Ruby的其他漂亮打印机不满意,我编写了自己的()并将其包括在内。该代码在MIT许可下是免费的(非常许可) 功能(所有可选):
- 设置线宽和换行方式,使对象和数组适合时保持在同一行上,不适合时每行换行一个值
- 如果愿意,请对对象键进行排序
- 对齐对象关键点(将冒号对齐)
- 将浮点数格式化为特定的小数位数,而不会弄乱整数
- “短”换行模式将开始括号和结束括号/大括号与值放在同一行,提供了一些人更喜欢的格式
- 对数组和对象、括号之间、冒号和逗号前后的间距进行精细控制
- 该功能可用于web浏览器和Node.js
(函数(导出){
exports.neatJSON=neatJSON;
函数neatJSON(值,opts){
opts=opts | |{}
如果(!('wrap'in opts))opts.wrap=80;
如果(opts.wrap==true)opts.wrap=-1;
如果(!('indent'在opts中))opts.indent='';
如果(!('arrayPadding'在选项中))opts.arrayPadding=('padding'在选项中)?opts.padding:0;
如果(!('objectPadding'在opts中))opts.objectPadding=('padding'在opts中)?opts.padding:0;
如果(!('afterComma'在选项中))opts.afterComma=('aroundComma'在选项中)?opts.aroundComma:0;
如果(!('beforecoma'在选项中))opts.beforecoma=('aroundComma'在选项中)?opts.aroundComma:0;
如果(!('afterColon'在选项中))opts.afterColon=('aroundColon'在选项中)?opts.aroundColon:0;
如果(!('beforeColon'在选项中))opts.beforeColon=('aroundColon'在选项中)?opts.aroundColon:0;
var apad=重复(“”,选择arrayPadding),
opad=重复(“”,opts.objectPadding),
逗号=重复(“”,选择逗号前的“+”,“+重复(“”,选择逗号后的“),
冒号=重复(“”,选择前冒号)+’:“”+重复(“”,选择后冒号);
返回构建(值“”);
函数构建(o,缩进){
如果(o==null | | o==undefined)返回缩进+'null';
否则{
交换机(o.constructor){
案件编号:
变量isFloat=(o==+o&&o!==(o|0));
返回缩进+((选项中的isFloat&('decimals'))?o.toFixed(选项小数):(o+“”);
案例阵列:
var片段=o.map(函数(v){返回构建(v,,)});
var oneLine=indent+'['+apad+pieces.join(逗号)+apad+']';
if(opts.wrap==false | | oneLine.length=1;
如果(次)str+=str;
其他的
const object = JSON.parse(jsonString)
console.dir(object, {depth: null, colors: true})
const jsonMarkup = require('json-markup')
const html = jsonMarkup({hello:'world'})
document.querySelector('#myElem').innerHTML = html
<link ref="stylesheet" href="style.css">
<div id="myElem></div>
https://raw.githubusercontent.com/mafintosh/json-markup/master/style.css
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>"
console.table()
function formatJSON(json,textarea) {
var nl;
if(textarea) {
nl = " ";
} else {
nl = "<br>";
}
var tab = "    ";
var ret = "";
var numquotes = 0;
var betweenquotes = false;
var firstquote = false;
for (var i = 0; i < json.length; i++) {
var c = json[i];
if(c == '"') {
numquotes ++;
if((numquotes + 2) % 2 == 1) {
betweenquotes = true;
} else {
betweenquotes = false;
}
if((numquotes + 3) % 4 == 0) {
firstquote = true;
} else {
firstquote = false;
}
}
if(c == '[' && !betweenquotes) {
ret += c;
ret += nl;
continue;
}
if(c == '{' && !betweenquotes) {
ret += tab;
ret += c;
ret += nl;
continue;
}
if(c == '"' && firstquote) {
ret += tab + tab;
ret += c;
continue;
} else if (c == '"' && !firstquote) {
ret += c;
continue;
}
if(c == ',' && !betweenquotes) {
ret += c;
ret += nl;
continue;
}
if(c == '}' && !betweenquotes) {
ret += nl;
ret += tab;
ret += c;
continue;
}
if(c == ']' && !betweenquotes) {
ret += nl;
ret += c;
continue;
}
ret += c;
} // i loop
return ret;
}
JSON.stringify(jsonobj,null,'\t')
Prism.highlightAll()
function pretty(ob, lvl = 0) {
let temp = [];
if(typeof ob === "object"){
for(let x in ob) {
if(ob.hasOwnProperty(x)) {
temp.push( getTabs(lvl+1) + x + ":" + pretty(ob[x], lvl+1) );
}
}
return "{\n"+ temp.join(",\n") +"\n" + getTabs(lvl) + "}";
}
else {
return ob;
}
}
function getTabs(n) {
let c = 0, res = "";
while(c++ < n)
res+="\t";
return res;
}
let obj = {a: {b: 2}, x: {y: 3}};
console.log(pretty(obj));
/*
{
a: {
b: 2
},
x: {
y: 3
}
}
*/
const HighlightedJSON = ({ json }: Object) => {
const highlightedJSON = jsonObj =>
Object.keys(jsonObj).map(key => {
const value = jsonObj[key];
let valueType = typeof value;
const isSimpleValue =
["string", "number", "boolean"].includes(valueType) || !value;
if (isSimpleValue && valueType === "object") {
valueType = "null";
}
return (
<div key={key} className="line">
<span className="key">{key}:</span>
{isSimpleValue ? (
<span className={valueType}>{`${value}`}</span>
) : (
highlightedJSON(value)
)}
</div>
);
});
return <div className="json">{highlightedJSON(json)}</div>;
};
console.log("data",data) // lets you unfold the object manually
var s = JSON.stringify(data,null,2) // format
var e = new Option(s).innerHTML // escape
document.body.insertAdjacentHTML('beforeend','<pre>'+e+'</pre>') // display
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);
npm install cli-highlight --save
const highlight = require('cli-highlight').highlight
console.logjson = (obj) => console.log(
highlight( JSON.stringify(obj, null, 4),
{ language: 'json', ignoreIllegals: true } ));
console.logjson({foo: "bar", someArray: ["string1", "string2"]});
<!-- here is a complete example pretty print with more space between lines-->
<!-- be sure to pass a json string not a json object -->
<!-- use line-height to increase or decrease spacing between json lines -->
<style type="text/css">
.preJsonTxt{
font-size: 18px;
text-overflow: ellipsis;
overflow: hidden;
line-height: 200%;
}
.boxedIn{
border: 1px solid black;
margin: 20px;
padding: 20px;
}
</style>
<div class="boxedIn">
<h3>Configuration Parameters</h3>
<pre id="jsonCfgParams" class="preJsonTxt">{{ cfgParams }}</pre>
</div>
<script language="JavaScript">
$( document ).ready(function()
{
$(formatJson);
<!-- this will do a pretty print on the json cfg params -->
function formatJson() {
var element = $("#jsonCfgParams");
var obj = JSON.parse(element.text());
element.html(JSON.stringify(obj, undefined, 2));
}
});
</script>
function prettifyJson(json, prettify) {
if (typeof json !== 'string') {
if (prettify) {
json = JSON.stringify(json, undefined, 4);
} else {
json = JSON.stringify(json);
}
}
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 = "<span>";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "<span class='text-danger'>";
} else {
cls = "<span>";
}
} else if (/true|false/.test(match)) {
cls = "<span class='text-primary'>";
} else if (/null/.test(match)) {
cls = "<span class='text-info'>";
}
return cls + match + "</span>";
}
);
}
let theJson = {
'username': 'elen',
'email': 'elen@test.com',
'state': 'married',
'profiles': [
{'name': 'elenLove', 'job': 'actor' },
{'name': 'elenDoe', 'job': 'spy'}
],
'hobbies': ['run', 'movies'],
'status': {
'home': {
'ownsHome': true,
'addresses': [
{'town': 'Mexico', 'address': '123 mexicoStr'},
{'town': 'Atlanta', 'address': '4B atlanta 45-48'},
]
},
'car': {
'ownsCar': true,
'cars': [
{'brand': 'Nissan', 'plate': 'TOKY-114', 'prevOwnersIDs': ['4532354531', '3454655344', '5566753422']},
{'brand': 'Benz', 'plate': 'ELEN-1225', 'prevOwnersIDs': ['4531124531', '97864655344', '887666753422']}
]
}
},
'active': true,
'employed': false,
};
username
email
state
profiles[]
profiles[].name
profiles[].job
hobbies[]
status{}
status{}.home{}
status{}.home{}.ownsHome
status{}.home{}.addresses[]
status{}.home{}.addresses[].town
status{}.home{}.addresses[].address
status{}.car{}
status{}.car{}.ownsCar
status{}.car{}.cars[]
status{}.car{}.cars[].brand
status{}.car{}.cars[].plate
status{}.car{}.cars[].prevOwnersIDs[]
active
employed
function jsonAnalyze(obj) {
let arr = [];
analyzeJson(obj, null, arr);
return logBeautifiedDotNotation(arr);
function analyzeJson(obj, parentStr, outArr) {
let opt;
if (!outArr) {
return "no output array given"
}
for (let prop in obj) {
opt = parentStr ? parentStr + '.' + prop : prop;
if (Array.isArray(obj[prop]) && obj[prop] !== null) {
let arr = obj[prop];
if ((Array.isArray(arr[0]) || typeof arr[0] == "object") && arr[0] != null) {
outArr.push(opt + '[]');
analyzeJson(arr[0], opt + '[]', outArr);
} else {
outArr.push(opt + '[]');
}
} else if (typeof obj[prop] == "object" && obj[prop] !== null) {
outArr.push(opt + '{}');
analyzeJson(obj[prop], opt + '{}', outArr);
} else {
if (obj.hasOwnProperty(prop) && typeof obj[prop] != 'function') {
outArr.push(opt);
}
}
}
}
function logBeautifiedDotNotation(arr) {
retStr = '';
arr.map(function (item) {
let dotsAmount = item.split(".").length - 1;
let dotsString = Array(dotsAmount + 1).join(' ');
retStr += dotsString + item + '\n';
console.log(dotsString + item)
});
return retStr;
}
}
jsonAnalyze(theJson);
const clsMap = [
[/^".*:$/, "key"],
[/^"/, "string"],
[/true|false/, "boolean"],
[/null/, "key"],
[/.*/, "number"],
]
const syntaxHighlight = obj => JSON.stringify(obj, null, 4)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, match => `<span class="${clsMap.find(([regex]) => regex.test(match))[1]}">${match}</span>`);
const clsMap = [
[/^".*:$/, "red"],
[/^"/, "green"],
[/true|false/, "blue"],
[/null/, "magenta"],
[/.*/, "darkorange"],
]
const syntaxHighlight = obj => JSON.stringify(obj, null, 4)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, match => `<span style="color:${clsMap.find(([regex]) => regex.test(match))[1]}">${match}</span>`);
const clsMap = [
[match => match.startsWith('"') && match.endsWith(':'), "red"],
[match => match.startsWith('"'), "green"],
[match => match === "true" || match === "false" , "blue"],
[match => match === "null", "magenta"],
[() => true, "darkorange"],
];
const syntaxHighlight = obj => JSON.stringify(obj, null, 4)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, match => `<span style="color:${clsMap.find(([fn]) => fn(match))[1]}">${match}</span>`);