사람이 쉽게 읽을 수있는 형식으로 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의 실제 동작보기
또는 아래에 제공된 전체 스 니펫 :
답변
Pumbaa80 사용자의 대답은 예쁘게 인쇄하고 싶은 물체 가 있다면 좋습니다 . 예쁘게 인쇄하려는 유효한 JSON 문자열 에서 시작하는 경우 먼저 이를 객체로 변환해야합니다.
var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);
문자열에서 JSON 객체를 작성한 다음 JSON stringify의 예쁜 글씨를 사용하여 문자열로 다시 변환합니다.
답변
답변
Pumbaa80의 답변을 기반으로 HTML이 아닌 console.log 색상 (Chrome에서 작동 함)을 사용하도록 코드를 수정했습니다. 콘솔 내에서 출력을 볼 수 있습니다. 더 많은 스타일을 추가하여 함수 내에서 _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이 콘솔에서 % 이스케이프를 지원하지 않는 것으로 나타났습니다. 이상해 … 아마도 이것이 나중에 작동 할 것입니다.
건배!
답변
var jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07", "postalCode": "75007", "countryCode": "FRA", "countryLabel": "France" };
document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);
HTML로 표시하는 경우 balise를 추가해야합니다 <pre></pre>
document.getElementById("result-after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, 2) +"</pre>"
예:
답변
JSONView Chrome 확장 프로그램을 사용합니다 .
편집 : 추가 jsonreport.js
또한 JSON 데이터를 보는 데 사용할 수있는 사람이 읽을 수있는 HTML5 보고서를 제공하는 온라인 독립형 JSON 프리티 프린트 뷰어 인 jsonreport.js를 출시했습니다.
새 JavaScript HTML5 보고서 형식에서 형식에 대한 자세한 내용을 읽을 수 있습니다 .
답변
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})}))"