Jak wydrukować JSON za pomocą JavaScript?

Jak wyświetlić JSON w formacie łatwym do odczytania (dla czytników ludzkich)? Szukam głównie wcięć i białych spacji, może nawet kolorów / stylów czcionek / itp.

Author: Shog9, 2011-01-27

24 answers

Pretty-drukowanie jest realizowane natywnie w JSON.stringify(). Trzeci argument umożliwia drukowanie pretty i ustawia odstępy do użycia:

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

Jeśli potrzebujesz podświetlenia składni, możesz użyć magii regex w ten sposób:

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

Zobacz w akcji tutaj: jsfiddle

Lub pełny fragment poniżej:

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; }
 3835
Author: user123444555621,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-31 10:48:56

ODPOWIEDŹ użytkownika Pumbaa80 jest świetna, jeśli masz obiekt chcesz ładnie wydrukować. Jeśli zaczynasz od poprawnego ciągu JSON , który chcesz wydrukować, musisz najpierw przekonwertować go na obiekt:

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

To buduje obiekt JSON z łańcucha, a następnie konwertuje go z powrotem do łańcucha za pomocą ładnego wydruku JSON stringify.

 186
Author: Rick Hanlon II,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-14 03:57:55

Na podstawie odpowiedzi Pumbaa80 zmodyfikowałem kod tak, aby korzystał z konsoli.log colours (na pewno działa na Chrome), a nie HTML. Wyjście można zobaczyć wewnątrz konsoli. Możesz edytować _variables wewnątrz funkcji dodając więcej stylizacji.

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

Oto bookmarklet, którego możesz użyć:

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

Użycie:

var obj = {a:1, 'b':'foo', c:[false,null, {d:{e:1.3e5}}]};
JSONstringify(obj);

Edit: właśnie próbowałem uciec od symbolu % z tej linii, po deklaracji zmiennych:

json = json.replace(/%/g, '%%');

Ale dowiaduję się, że Chrome nie wspiera % ucieczka w konsoli. Dziwne... Może to zadziała w przyszłości.

Zdrówko!

Tutaj wpisz opis obrazka

 23
Author: Milen Boev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-19 22:03:38

Używam rozszerzenia Jsonview Chrome (jest tak ładne, jak tylko się da:):

Edit: added jsonreport.js

Wydałem również samodzielną przeglądarkę JSON pretty print viewer, jsonreport.js, który zapewnia czytelny dla człowieka raport HTML5, którego możesz użyć do przeglądania dowolnych danych JSON.

Możesz przeczytać więcej o formacie w nowy format raportu JavaScript HTML5.

 20
Author: mythz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-11 00:46:22

Możesz użyć console.dir(), który jest skrótem dla console.log(util.inspect()). (Jedyną różnicą jest to, że omija dowolną niestandardową funkcję inspect() zdefiniowaną na obiekcie.)

Używa podświetlania składni, inteligentne wcięcia, usuwa cudzysłowy z kluczy i sprawia, że wyjście jest tak piękne, jak tylko się da.

const object = JSON.parse(jsonString)

console.dir(object, {depth: null, colors: true})

Oraz dla wiersza poleceń:

cat package.json | node -e "process.stdin.pipe(new stream.Writable({write: chunk => console.dir(JSON.parse(chunk), {depth: null, colors: true})}))"

 16
Author: adius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-02 13:18:57

Lepszy sposób.

Pretty JSON Array in Javascript

JSON.stringify(jsonobj,null,'\t')
 13
Author: Charmie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-21 10:19:59
var jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07",  "postalCode": "75007", "countryCode": "FRA",  "countryLabel": "France" };

document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);

W przypadku wyświetlania w HTML, należy dodać balise <pre></pre>

document.getElementById("result-after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, 2) +"</pre>"

Przykład:

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>
 9
Author: Adel MANI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-12 03:29:50
 5
Author: gavenkoa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-10 14:11:26

Niezadowolony z innych ładnych drukarek dla Rubiego, napisałem własną (NeatJSON ), a następnieprzeportowałem ją do JavaScript , w tymdarmowy program do formatowania online . Kod jest wolny na licencji MIT (dość permissive).

Funkcje (wszystkie opcjonalne):

  • ustawia szerokość linii i zawija w sposób, który utrzymuje obiekty i tablice w tej samej linii, gdy pasują, owijając jedną wartość w linii, gdy nie.
  • Sortuj klucze obiektów, jeśli chcesz.
  • Align obiekt klawisze (Ustaw dwukropki).
  • Formatuj liczby zmiennoprzecinkowe na określoną liczbę miejsc po przecinku, bez mieszania liczb całkowitych.
  • "Krótki" tryb owijania umieszcza nawiasy/klamry otwierające i zamykające w tej samej linii co wartości, zapewniając format, który niektórzy preferują.
  • Szczegółowa kontrola nad odstępami dla tablic i obiektów, między nawiasami, przed / za dwukropkami i przecinkami.
  • funkcja jest dostępna zarówno dla przeglądarek internetowych, jak i dla węzła.js.

Skopiuję kod źródłowy tutaj, aby nie był to tylko link do biblioteki, ale zachęcam do przejścia na stronę projektu GitHub, ponieważ będzie on na bieżąco aktualizowany, a poniższy kod nie.

(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);
 4
Author: Phrogz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-19 21:49:25

Wielkie dzięki @ all! W oparciu o poprzednie odpowiedzi, oto inna metoda wariantowa dostarczająca niestandardowe reguły zastępcze jako parametr:

 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;
 }
 3
Author: webfan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-29 23:13:10

JSON Douglasa Crockforda w Bibliotece JavaScript ładnie wydrukuje JSON za pomocą metody stringify.

Możesz również znaleźć przydatne odpowiedzi na to starsze pytanie: Jak mogę wydrukować JSON w skrypcie powłoki (unix)?

 2
Author: zcopley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:45

To działa dobrze:

console.table()

Czytaj więcej tutaj: https://developer.mozilla.org/pt-BR/docs/Web/API/Console/table

 2
Author: Ricardo Pontual,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-15 11:51:24

Wpadłem dziś na problem z kodem @Pumbaa80. Próbuję zastosować podświetlanie składni JSON do danych, które renderuję w widoku Mithril , więc muszę utworzyć węzły DOM dla wszystkiego na wyjściu JSON.stringify.

Podzieliłem naprawdę długi regex na jego części składowe.

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)

Code in context on Github here

 2
Author: Just Jake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-03 04:35:55

Jeśli potrzebujesz tego do pracy w textarea zaakceptowane rozwiązanie nie będzie działać.

<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;
}
 1
Author: Kolob Canyon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-05 00:13:26

Oto prosty komponent formatu / koloru JSON napisany w Reaccie:

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

Zobacz to działa w tym kodzie: https://codepen.io/benshope/pen/BxVpjo

Mam nadzieję, że to pomoże!
 1
Author: benshope,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-13 07:36:53

Możesz użyć JSON.stringify(Twój obiekt, null, 2) Drugi parametr może być używany jako funkcja zastępcza, która przyjmuje key i Val jako parametry.To może być użyte w przypadku, gdy chcesz zmodyfikować coś w swoim obiekcie JSON.

 1
Author: jenil christo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-12 03:58:54

Oto user123444555621 ' s awesome HTML one dostosowane do terminali. Przydatne do debugowania skryptów węzłów:

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

Użycie:

// thing = any json OR string of json
prettyJ(thing);
 1
Author: James Heazlewood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-13 07:35:34

Polecam używanie HighlightJS. Używa tej samej zasady jako akceptowanej odpowiedzi, ale działa również dla wielu innych języków i ma wiele predefiniowanych schematów kolorów . Jeśli używasz RequireJS , możesz wygenerować kompatybilny moduł z

python3 tools/build.py -tamd json xml <specify other language here>
Generowanie opiera się na Python3 i Javie. Dodaj -n, Aby wygenerować wersję niemnifikowaną.
 0
Author: Rok Strniša,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-03 13:32:55

To jest ładne:

Https://github.com/mafintosh/json-markup z 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>

Przykładowy arkusz stylów można znaleźć tutaj

https://raw.githubusercontent.com/mafintosh/json-markup/master/style.css
 0
Author: wires,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-22 22:14:24

Jeśli szukasz ładnej biblioteki do poprawienia json na stronie internetowej...

Pryzmat.js jest całkiem niezły.

Http://prismjs.com/

Znalazłem używając JSON.stringify (obj, undefined, 2), aby uzyskać wcięcie, a następnie za pomocą pryzmatu dodać temat było dobrym podejściem.

Jeśli ładujesz JSON przez wywołanie ajax, możesz uruchomić jedną z metod użytkowych Prism, aby poprawić

Na przykład:

Prism.highlightAll()
 0
Author: chim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-19 16:24:06

Oto jak można drukować bez użycia natywnej funkcji.

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
    }
  }
*/
 0
Author: everlasto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-24 20:11:30

Najprostszy sposób wyświetlania obiektu do celów debugowania:

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

Jeśli chcesz wyświetlić obiekt w DOM, powinieneś wziąć pod uwagę, że może on zawierać ciągi znaków, które będą interpretowane jako HTML. Dlatego musisz wykonać jakąś ucieczkę ...

var s = JSON.stringify(data,null,2) // format
var e = new Option(s).innerHTML // escape
document.body.insertAdjacentHTML('beforeend','<pre>'+e+'</pre>') // display
 0
Author: nobar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-04 03:48:02

Jeśli używasz net.sf.json, możesz wydrukować w następujący sposób (używając 4 spacji):

JSONObject work = JSONObject.fromObject("{\"hi\":\"there\",\"more\":\"stuff\"}");
log.info("WORK="+work.toString(4));
 -2
Author: Fred Haslam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-28 07:00:00

Użyj Newtonsoft.JSON dll. to działa dobrze w IE i Chrome

Umieść ten kod w widoku brzytwy

    if (Model.YourJsonSting!= null)
        {
            <pre>
            <code style="display:block;white-space:pre-wrap">
                      @JToken.Parse(Model.YourJsonSting).ToString(Formatting.Indented)
                </code>
            </pre>
        }
 -6
Author: user3942119,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-11 20:57:12