sourcecode

JavaScript를 사용한 예쁜 인쇄 JSON

copyscript 2022. 11. 6. 13:37
반응형

JavaScript를 사용한 예쁜 인쇄 JSON

JSON을 읽기 쉬운(인간 리더용) 형식으로 표시하려면 어떻게 해야 합니까?주로 오목한 부분이나 공백 부분을 찾고 있습니다.컬러나 폰트 스타일은 균등할 수 있습니다.

예쁜 인쇄는 에 네이티브로 실장되어 있습니다.세 번째 인수는 예쁜 인쇄를 활성화하고 사용할 간격을 설정합니다.

var str = JSON.stringify(obj, null, 2); // spacing level = 2

구문 강조 표시가 필요한 경우 다음과 같은 regex 매직을 사용할 수 있습니다.

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    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; }

예쁘게 인쇄하고 싶은 오브젝트가 있다면 사용자 Pumba80의 답변은 훌륭합니다.올바르게 인쇄하는 유효한 JSON 문자열에서 시작하는 경우 먼저 개체로 변환해야 합니다.

var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);  

문자열에서 JSON 개체를 만든 다음 JSON stringify의 예쁜 인쇄를 사용하여 문자열로 다시 변환합니다.

더 좋은 방법이야.

Javascript에서 JSON 어레이를 예쁘게 꾸미다

JSON.stringify(jsonobj,null,'\t')
var 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>

Pumbaa80의 답변을 바탕으로 코드를 수정하여 HTML이 아닌 console.log 컬러를 사용하도록 하였습니다.함수 내의 _변수를 편집하여 스타일을 추가할 수 있습니다.

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이 콘솔에서 %탈출하는 것을 지원하지 않는다는 것을 알게 되었습니다.이상하네...아마도 이것은 미래에 효과가 있을 것이다.

건배!

여기에 이미지 설명 입력

하시면 됩니다.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 데이터를 표시하기 위해 사용할 수 있는 사람이 읽을 수 있는 HTML5 보고서를 제공하는 JSON 프리티 프린트 뷰어인 jsonreport.js도 출시했습니다.

형식에 대한 자세한 내용은 New JavaScript HTML5 Report Format을 참조하십시오.

여기 사용자 123444555621이 단말기에 적합한 멋진 HTML이 있습니다.노드 스크립트 디버깅에 편리:

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);

ES5 를 사용하고 있는 경우는, JSON.stringify 에 전화하기만 하면 됩니다.

  • 두 번째 arg: 리페이서, null로 설정,
  • 세 번째 arg: 공백, 탭을 사용합니다.
JSON.stringify(anObject, null, '\t');

출처 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

다음과 같은 것을 찾고 계신 것 같습니다.

JSON.stringify(obj, null, '\t');

이것은 들여쓰기 탭을 사용하여 JSON 문자열을 "예쁜 인쇄"합니다.

탭 대신 공백을 사용하는 경우 원하는 공간 수에 숫자를 사용할 수도 있습니다.

JSON.stringify(obj, null, 2);

하시면 됩니다.JSON.stringify(your object, null, 2)두 번째 파라미터는 키와 Val을 파라미터로 사용하는 리페이서 함수로 사용할 수 있습니다.이것은 JSON 개체 내에서 무언가를 수정하려는 경우에 사용할 수 있습니다.

자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify를 참조해 주세요.

디버깅 목적으로 사용하는 것은 다음과 같습니다.

console.syslog%o", 데이터);

다른 예쁜 Ruby용 프린터에 만족하지 못하고 직접 (NeatJSON)을 작성하여 무료 온라인 포맷터를 포함한 JavaScript로 포팅했습니다.이 코드는 MIT 라이선스에 따라 무료입니다(완전 허용).

기능(모두 옵션):

  • 줄 너비를 설정하고 개체와 배열이 들어맞을 때 동일한 줄 위에 유지되도록 줄 바꿈합니다. 맞지 않을 때는 한 줄에 하나의 값을 줄 바꿈합니다.
  • 원하는 경우 개체 키를 정렬할 수 있습니다.
  • 객체 키 정렬(콜론 정렬)
  • 정수를 흐트러뜨리지 않고 부동소수점 숫자의 형식을 특정 소수점 수로 지정합니다.
  • '짧은' 줄 바꿈 모드는 개폐 괄호/괄호를 값과 같은 줄에 배치하여 일부에서 선호하는 형식을 제공합니다.
  • 각 괄호 사이, 콜론 및 콤마의 전후, 어레이 및 오브젝트의 간격을 세밀하게 제어합니다.
  • 이 기능은 웹 브라우저와 Node.js 모두에서 사용할 수 있습니다.

여기에 소스 코드를 복사하여 단순히 라이브러리에 대한 링크가 아니라 GitHub 프로젝트 페이지로 이동하는 것이 좋습니다.그것은 최신 상태로 유지되고 아래 코드는 그렇지 않습니다.

(function(exports){
exports.neatJSON = neatJSON;

function neatJSON(value,opts){
  opts = opts || {}
  if (!('wrap'          in opts)) opts.wrap = 80;
  if (opts.wrap==true) opts.wrap = -1;
  if (!('indent'        in opts)) opts.indent = '  ';
  if (!('arrayPadding'  in opts)) opts.arrayPadding  = ('padding' in opts) ? opts.padding : 0;
  if (!('objectPadding' in opts)) opts.objectPadding = ('padding' in opts) ? opts.padding : 0;
  if (!('afterComma'    in opts)) opts.afterComma    = ('aroundComma' in opts) ? opts.aroundComma : 0;
  if (!('beforeComma'   in opts)) opts.beforeComma   = ('aroundComma' in opts) ? opts.aroundComma : 0;
  if (!('afterColon'    in opts)) opts.afterColon    = ('aroundColon' in opts) ? opts.aroundColon : 0;
  if (!('beforeColon'   in opts)) opts.beforeColon   = ('aroundColon' in opts) ? opts.aroundColon : 0;

  var apad  = repeat(' ',opts.arrayPadding),
      opad  = repeat(' ',opts.objectPadding),
      comma = repeat(' ',opts.beforeComma)+','+repeat(' ',opts.afterComma),
      colon = repeat(' ',opts.beforeColon)+':'+repeat(' ',opts.afterColon);

  return build(value,'');

  function build(o,indent){
    if (o===null || o===undefined) return indent+'null';
    else{
      switch(o.constructor){
        case Number:
          var isFloat = (o === +o && o !== (o|0));
          return indent + ((isFloat && ('decimals' in opts)) ? o.toFixed(opts.decimals) : (o+''));

        case Array:
          var pieces  = o.map(function(v){ return build(v,'') });
          var oneLine = indent+'['+apad+pieces.join(comma)+apad+']';
          if (opts.wrap===false || oneLine.length<=opts.wrap) return oneLine;
          if (opts.short){
            var indent2 = indent+' '+apad;
            pieces = o.map(function(v){ return build(v,indent2) });
            pieces[0] = pieces[0].replace(indent2,indent+'['+apad);
            pieces[pieces.length-1] = pieces[pieces.length-1]+apad+']';
            return pieces.join(',\n');
          }else{
            var indent2 = indent+opts.indent;
            return indent+'[\n'+o.map(function(v){ return build(v,indent2) }).join(',\n')+'\n'+indent+']';
          }

        case Object:
          var keyvals=[],i=0;
          for (var k in o) keyvals[i++] = [JSON.stringify(k), build(o[k],'')];
          if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
          keyvals = keyvals.map(function(kv){ return kv.join(colon) }).join(comma);
          var oneLine = indent+"{"+opad+keyvals+opad+"}";
          if (opts.wrap===false || oneLine.length<opts.wrap) return oneLine;
          if (opts.short){
            var keyvals=[],i=0;
            for (var k in o) keyvals[i++] = [indent+' '+opad+JSON.stringify(k),o[k]];
            if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
            keyvals[0][0] = keyvals[0][0].replace(indent+' ',indent+'{');
            if (opts.aligned){
              var longest = 0;
              for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
              var padding = repeat(' ',longest);
              for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
            }
            for (var i=keyvals.length;i--;){
              var k=keyvals[i][0], v=keyvals[i][1];
              var indent2 = repeat(' ',(k+colon).length);
              var oneLine = k+colon+build(v,'');
              keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colon+build(v,indent2).replace(/^\s+/,''));
            }
            return keyvals.join(',\n') + opad + '}';
          }else{
            var keyvals=[],i=0;
            for (var k in o) keyvals[i++] = [indent+opts.indent+JSON.stringify(k),o[k]];
            if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
            if (opts.aligned){
              var longest = 0;
              for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
              var padding = repeat(' ',longest);
              for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
            }
            var indent2 = indent+opts.indent;
            for (var i=keyvals.length;i--;){
              var k=keyvals[i][0], v=keyvals[i][1];
              var oneLine = k+colon+build(v,'');
              keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colon+build(v,indent2).replace(/^\s+/,''));
            }
            return indent+'{\n'+keyvals.join(',\n')+'\n'+indent+'}'
          }

        default:
          return indent+JSON.stringify(o);
      }
    }
  }

  function repeat(str,times){ // http://stackoverflow.com/a/17800645/405017
    var result = '';
    while(true){
      if (times & 1) result += str;
      times >>= 1;
      if (times) str += str;
      else break;
    }
    return result;
  }
  function padRight(pad, str){
    return (str + pad).substring(0, pad.length);
  }
}
neatJSON.version = "0.5";

})(typeof exports === 'undefined' ? this : exports);

동작은 양호합니다.

console.table()

자세한 내용은 이쪽:https://developer.mozilla.org/pt-BR/docs/Web/API/Console/table

모두 감사합니다!위의 답변에 기초하여 커스텀 치환 규칙을 파라미터로 제공하는 다른 변형 방법을 다음에 나타냅니다.

 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 '&nbsp';
          }
       } 

    ],

    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;
 }

다음은 리액트로 작성된 간단한 JSON 형식/컬러 컴포넌트입니다.

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>;
};

다음 CodePen에서 보실 수 있습니다.

도움이 됐으면 좋겠네요!

콘솔에 적합한 구문 강조 표시를 가진 솔루션을 찾을 수 없었습니다.여기 2p가 있습니다.

CLI 설치 및 추가 - 의존관계 강조

npm install cli-highlight --save

logjson을 글로벌하게 정의하다

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"]});

산출량

JavaScript 라이브러리의 Douglas Crockford의 JSON은 stringify 메서드를 통해 JSON을 인쇄합니다.

이 오래된 질문에 대한 답변도 도움이 될 수 있습니다.(unix) 셸 스크립트로 JSON을 예쁘게 인쇄하려면 어떻게 해야 합니까?

오늘 @Pumbaa80의 코드에 문제가 발생했습니다.Mithril 뷰에서 렌더링하고 있는 데이터에 JSON 구문 강조 표시를 적용하려고 합니다.따라서 모든 데이터에 대해 DOM 노드를 작성해야 합니다.JSON.stringify산출량.

매우 긴 regex도 부품으로 분할했습니다.

render_json = (data) ->
  # wraps JSON data in span elements so that syntax highlighting may be
  # applied. Should be placed in a `whitespace: pre` context
  if typeof(data) isnt 'string'
    data = JSON.stringify(data, undefined, 2)
  unicode =     /"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?/
  keyword =     /\b(true|false|null)\b/
  whitespace =  /\s+/
  punctuation = /[,.}{\[\]]/
  number =      /-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/

  syntax = '(' + [unicode, keyword, whitespace,
            punctuation, number].map((r) -> r.source).join('|') + ')'
  parser = new RegExp(syntax, 'g')

  nodes = data.match(parser) ? []
  select_class = (node) ->
    if punctuation.test(node)
      return 'punctuation'
    if /^\s+$/.test(node)
      return 'whitespace'
    if /^\"/.test(node)
      if /:$/.test(node)
        return 'key'
      return 'string'

    if /true|false/.test(node)
      return 'boolean'

     if /null/.test(node)
       return 'null'
     return 'number'
  return nodes.map (node) ->
    cls = select_class(node)
    return Mithril('span', {class: cls}, node)

여기 Github의 컨텍스트에 맞는 코드

만약 당신이 웹페이지에서 json을 예쁘게 해줄 멋진 도서관을 찾고 있다면...

Prism.js 꽤 괜찮네요.

http://prismjs.com/

JSON.stringify(obj, defined, 2)를 사용하여 들여쓰기를 하고 프리즘을 사용하여 테마를 추가하는 것이 좋은 방법이라는 것을 알았습니다.

만약 당신이 Ajax 호출을 통해 JSON에 로드한다면, 당신은 프리즘의 유틸리티 메서드 중 하나를 실행하여 예쁘게 만들 수 있습니다.

예를 들어 다음과 같습니다.

Prism.highlightAll()

제가 보여드리고 싶은 건jsonAnalyze이 방법에서는 JSON 구조만 예쁘게 인쇄하지만 경우에 따라서는 JSON 전체를 인쇄하는 것보다 더 유용할 수 있습니다.

다음과 같은 복잡한 JSON이 있다고 가정해 보겠습니다.

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

이게 바로jsonAnalyze()코드:

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);

텍스트 영역에서 이 작업을 수행해야 하는 경우 승인된 솔루션은 작동하지 않습니다.

<textarea id='textarea'></textarea>

$("#textarea").append(formatJSON(JSON.stringify(jsonobject),true));

function formatJSON(json,textarea) {
    var nl;
    if(textarea) {
        nl = "&#13;&#10;";
    } else {
        nl = "<br>";
    }
    var tab = "&#160;&#160;&#160;&#160;";
    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;
}

이거 좋네요.

https://github.com/mafintosh/json-markup 에서mafintosh

const jsonMarkup = require('json-markup')
const html = jsonMarkup({hello:'world'})
document.querySelector('#myElem').innerHTML = html

HTML

<link ref="stylesheet" href="style.css">
<div id="myElem></div>

예제 스타일시트는 여기에서 찾을 수 있습니다.

https://raw.githubusercontent.com/mafintosh/json-markup/master/style.css

에서 강조 표시 및 미화HTML사용.Bootstrap:

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>";
        }
    );
}

@user123444555621을 기반으로 합니다.조금 더 모던합니다.

const clsMap = [
    [/^".*:$/, "key"],
    [/^"/, "string"],
    [/true|false/, "boolean"],
    [/null/, "key"],
    [/.*/, "number"],
]

const syntaxHighlight = obj => JSON.stringify(obj, null, 4)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .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>`);

또한 js 내의 색상을 지정할 수 있습니다(CSS 불필요).

const clsMap = [
    [/^".*:$/, "red"],
    [/^"/, "green"],
    [/true|false/, "blue"],
    [/null/, "magenta"],
    [/.*/, "darkorange"],
]

const syntaxHighlight = obj => JSON.stringify(obj, null, 4)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .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>`);

regex가 적은 버전입니다.

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, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .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>`);

Laravel, Codeigniter Html용:<pre class="jsonPre"> </pre>

컨트롤러: 컨트롤러에서 다음과 같이 JSON 값을 반환합니다.

return json_encode($data, JSON_PRETTY_PRINT);

스크립트:<script> $('.jsonPre').html(result); </script>

결과는 다음과 같습니다.

결과는 다음과 같습니다.

사람이 읽을 수 있는 JSON 출력을 1라인 코드(컬러 없음):

document.documentElement.innerHTML='<pre>'+JSON.stringify(obj, null, 2)+'</pre>';

네이티브 기능을 사용하지 않고 인쇄할 수 있는 방법은 다음과 같습니다.

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
    }
  }
*/

디버깅을 위해 개체를 표시하는 가장 간단한 방법은 다음과 같습니다.

console.log("data",data) // lets you unfold the object manually

개체를 DOM에 표시하려면 HTML로 해석되는 문자열을 포함할 수 있음을 고려해야 합니다. 따라서 일부 이스케이프를 수행해야 합니다.

var s = JSON.stringify(data,null,2) // format
var e = new Option(s).innerHTML // escape
document.body.insertAdjacentHTML('beforeend','<pre>'+e+'</pre>') // display
<!-- 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>

언급URL : https://stackoverflow.com/questions/4810841/pretty-print-json-using-javascript

반응형