Cómo registrar el contenido de un objeto JSON en el nodo.js?


Es posible imprimir un contenido de objetos, por ejemplo, métodos y atributos en el nodo.js?

En este momento estoy tratando de imprimir el objeto de sesión y obtener lo siguiente:

console.log("Session:" + session);
> Session:[object Object]

Tal vez de una manera similar a print_r(array) en PHP, o usando .toString en Java.

 143
Author: Peter Mortensen, 2011-09-15

6 answers

Prueba este:

console.log("Session: %j", session);

Si el objeto se puede convertir en JSON, funcionará.

 245
Author: Alexander Sulfrian,
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-07-16 10:26:16
function prettyJSON(obj) {
    console.log(JSON.stringify(obj, null, 2));
}

// obj -> value to convert to a JSON string
// null -> (do nothing)
// 2 -> 2 spaces per indent level

JSON.stringify en MDN

 101
Author: ccgillett,
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-17 07:58:18

Para tener una salida más similar a la raw console.log(obj) normalmente uso console.log('Status: ' + util.inspect(obj)) (JSON es ligeramente diferente).

 32
Author: lapo,
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
2012-04-13 09:51:12

Esto funcionará con cualquier objeto:

    var util = require("util");
    console.log(util.inspect(myObject, {showHidden: false, depth: null}));
 19
Author: Marwen Trabelsi,
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-06-23 05:50:06

Consola.dir() es la forma más directa.

 6
Author: rainabba,
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-12-17 02:56:25
console.log(obj);

Ejecutar: aplicación de nodo.js > salida.txt

 0
Author: Ростислав Борніцький,
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-16 13:14:25