¿Cómo puedo imprimir JSON con JavaScript?


¿Cómo puedo mostrar JSON en un formato fácil de leer (para lectores humanos)? Estoy buscando principalmente sangría y espacios en blanco, con tal vez incluso colores / font-styles / etc.

Author: Shog9, 2011-01-27

24 answers

Pretty-printing se implementa de forma nativa en JSON.stringify(). El tercer argumento habilita la impresión bonita y establece el espaciado a usar:

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

Si necesita resaltado de sintaxis, puede usar alguna magia de expresiones regulares como esta:

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

Ver en acción aquí: jsfiddle

O un fragmento completo proporcionado a continuación:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-31 10:48:56

La respuesta del usuario Pumbaa80 es genial si tienes un objeto que quieres que esté bastante impreso. Si está comenzando desde una cadena JSON válida que desea imprimir bastante, primero debe convertirla en un objeto:

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

Esto construye un objeto JSON a partir de la cadena, y luego lo convierte de nuevo en una cadena utilizando la impresión pretty de 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-14 03:57:55

Basado en la respuesta de Pumbaa80 he modificado el código para usar la consola.colores de registro (trabajando en Chrome con seguridad) y no HTML. La salida se puede ver dentro de la consola. Puede editar las _variables dentro de la función añadiendo un poco más de estilo.

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

Aquí hay un bookmarklet que puede usar:

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

Uso:

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

Edit: Acabo de intentar escapar del símbolo % con esta línea, después de la declaración de variables:

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

Pero me entero de que Chrome no es compatible % escapando en la consola. Extraño... Tal vez esto funcione en el futuro.

Salud!

introduzca la descripción de la imagen aquí

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-19 22:03:38

Uso la extensión JsonView Chrome (es tan bonita como se pone:):

Editar: agregado jsonreport.js

También he lanzado un visor de impresión JSON independiente en línea, jsonreport.js, que proporciona un informe HTML5 legible por humanos que puede usar para ver cualquier dato JSON.

Puede leer más sobre el formato en Nuevo Formato de Informe 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-11 00:46:22

Puede usar console.dir(), que es un atajo para console.log(util.inspect()). (La única diferencia es que omite cualquier función personalizada inspect() definida en un objeto.)

Utiliza resaltado de sintaxis, sangría inteligente, elimina las comillas de las claves y simplemente hace que la salida sea lo más bonita posible.

const object = JSON.parse(jsonString)

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

Y para la línea de comandos:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-02 13:18:57

Mejor manera.

Embellecer la matriz JSON en 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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);

En caso de mostrarse en HTML, debe agregar un balise <pre></pre>

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

Ejemplo:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-12 03:29:50

Para el propósito de depuración uso:

console.debug("%o", data);
 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-10 14:11:26

Insatisfecho con otras impresoras bonitas para Ruby, escribí la mía propia ( NeatJSON) y luego la porté a JavaScript incluyendo un formateador en línea gratuito. El código es libre bajo la licencia MIT (bastante permisiva).

Características (todas opcionales):

  • Establezca un ancho de línea y ajuste de una manera que mantenga los objetos y matrices en la misma línea cuando encajen, ajustando un valor por línea cuando no lo hagan.
  • Ordenar las claves de objeto si lo desea.
  • Alinear objeto teclas (alinea los dos puntos).
  • Formatee los números de coma flotante a un número específico de decimales, sin estropear los enteros.
  • El modo de envoltura'Corto' pone los corchetes/llaves de apertura y cierre en la misma línea que los valores, proporcionando un formato que algunos prefieren.
  • Control granular sobre el espaciado para matrices y objetos, entre corchetes, antes/después de dos puntos y comas.
  • La función está disponible tanto para los navegadores web como para el nodo.js.

Voy a copiar el código fuente aquí para que esto no sea solo un enlace a una biblioteca, pero te animo a ir a la página del proyecto GitHub , ya que se mantendrá actualizado y el código a continuación no.

(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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-19 21:49:25

Muchas gracias a todos! Basado en las respuestas anteriores, aquí hay otro método variante que proporciona reglas de reemplazo personalizadas como parámetro:

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-29 23:13:10

El JSON de Douglas Crockford en la biblioteca JavaScript imprimirá bastante JSON a través del método stringify.

También puede encontrar útiles las respuestas a esta pregunta anterior: ¿Cómo puedo imprimir JSON en un script de shell (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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:45

Funciona bien:

console.table()

Lea más aquí: 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-15 11:51:24

Me encontré con un problema hoy con el código de @Pumbaa80. Estoy tratando de aplicar resaltado de sintaxis JSON a los datos que estoy renderizando en una vista Mithril, por lo que necesito crear nodos DOM para todo en la salida JSON.stringify.

Divido la expresión regular realmente larga en sus partes componentes también.

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)

Código en contexto en Github aquí

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-03 04:35:55

Si necesita que esto funcione en un área de texto, la solución aceptada no funcionará.

<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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-05 00:13:26

Aquí hay un simple componente de formato / color JSON escrito en React:

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

Ver que funciona en este CodePen: https://codepen.io/benshope/pen/BxVpjo

Espero que ayude!

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-13 07:36:53

Puede usar JSON.stringify (su objeto, null, 2) El segundo parámetro se puede utilizar como una función de reemplazo que toma key y Val como parámetros.Esto se puede usar en caso de que desee modificar algo dentro de su objeto 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-12 03:58:54

Aquí está el impresionante HTML de user123444555621 adaptado para terminales. Útil para depurar scripts de nodos:

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

Uso:

// 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-13 07:35:34

Recomiendo usar HighlightJS. Utiliza el mismo principioque la respuesta aceptada, pero funciona también para muchos otros idiomas, y tiene muchos esquemas de color predefinidos. Si utiliza RequireJS , puede generar un módulo compatible con

python3 tools/build.py -tamd json xml <specify other language here>

La generación se basa en Python3 y Java. Agregue -n para generar una versión no minificada.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-03 13:32:55

Esto es bueno:

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

La hoja de estilos de ejemplo se puede encontrar aquí

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-22 22:14:24

Si estás buscando una buena biblioteca para embellecer json en una página web...

Prisma.js es bastante bueno.

Http://prismjs.com/

Encontré usando JSON.stringify (obj, undefined, 2) para obtener la sangría, y luego usar prism para agregar un tema fue un buen enfoque.

Si está cargando en JSON a través de una llamada ajax, puede ejecutar uno de los métodos de utilidad de Prism para embellecer

Por ejemplo:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-19 16:24:06

Aquí es cómo se puede imprimir sin utilizar la función nativa.

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-24 20:11:30

La forma más sencilla de mostrar un objeto con fines de depuración:

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

Si desea mostrar el objeto en el DOM, debe considerar que podría contener cadenas que se interpretarían como HTML. Por lo tanto, necesitas hacer algo de escape...

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-04 03:48:02

Si utiliza net.ficción.json, puede imprimir de la siguiente manera (usando una sangría de 4 espacios):

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-28 07:00:00

Utilice Newtonsoft.Json dll. esto funciona bien en IE y Chrome

Ponga este código en su vista razor

    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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-11 20:57:12