Print JSON parsed object?

JavascriptJsonParsingPrinting

Javascript Problem Overview


I've got a javascript object which has been JSON parsed using JSON.parse I now want to print the object so I can debug it (something is going wrong with the function). When I do the following...

for (property in obj) {
    output += property + ': ' + obj[property]+'; ';
}
console.log(output);

I get multiple [object Object]'s listed. I'm wondering how would I print this in order to view the contents?

Javascript Solutions


Solution 1 - Javascript

You know what JSON stands for? JavaScript Object Notation. It makes a pretty good format for objects.

JSON.stringify(obj) will give you back a string representation of the object.

Solution 2 - Javascript

Most debugger consoles support displaying objects directly. Just use

console.log(obj);

Depending on your debugger this most likely will display the object in the console as a collapsed tree. You can open the tree and inspect the object.

Solution 3 - Javascript

If you want a pretty, multiline JSON with indentation then you can use JSON.stringify with its 3rd argument:

> JSON.stringify(value[, replacer[, space]])

For example:

var obj = {a:1,b:2,c:{d:3, e:4}};

JSON.stringify(obj, null, "    ");

or

JSON.stringify(obj, null, 4);

will give you following result:

"{
    "a": 1,
    "b": 2,
    "c": {
        "d": 3,
        "e": 4
    }
}"

In a browser console.log(obj) does even better job, but in a shell console (node.js) it doesn't.

Solution 4 - Javascript

try console.dir() instead of console.log()

console.dir(obj);

MDN says console.dir() is supported by:

  • FF8+
  • IE9+
  • Opera
  • Chrome
  • Safari

Solution 5 - Javascript

to Print JSON parsed object just type

console.log( JSON.stringify(data, null, " ") );

and you will get output very clear

Solution 6 - Javascript

Use string formats;

console.log("%s %O", "My Object", obj);

Chrome has Format Specifiers with the following;

  • %s Formats the value as a string.
  • %d or %i Formats the value as an integer.
  • %f Formats the value as a floating point value.
  • %o Formats the value as an expandable DOM element (as in the Elements panel).
  • %O Formats the value as an expandable JavaScript object.
  • %c Formats the output string according to CSS styles you provide.

Firefox also has String Substitions which have similar options.

  • %o Outputs a hyperlink to a JavaScript object. Clicking the link opens an inspector.
  • %d or %i Outputs an integer. Formatting is not yet supported.
  • %s Outputs a string.
  • %f Outputs a floating-point value. Formatting is not yet supported.

Safari has printf style formatters

  • %d or %i Integer
  • %[0.N]f Floating-point value with N digits of precision
  • %o Object
  • %s String

Solution 7 - Javascript

Nice and simple:

console.log("object: %O", obj)

Solution 8 - Javascript

Just use

console.info("CONSOLE LOG : ")
console.log(response);
console.info("CONSOLE DIR : ")
console.dir(response);

and you will get this in chrome console :

CONSOLE LOG : 
facebookSDK_JS.html:56 Object {name: "Diego Matos", id: "10155988777540434"}
facebookSDK_JS.html:57 CONSOLE DIR : 
facebookSDK_JS.html:58 Objectid: "10155988777540434"name: "Diego Matos"__proto__: Object

Solution 9 - Javascript

If you want to debug why not use console debug

window.console.debug(jsonObject);

Solution 10 - Javascript

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);

Solution 11 - Javascript

The following code will display complete json data in alert box

var data= '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

json = JSON.parse(data);
window.alert(JSON.stringify(json));

Solution 12 - Javascript

If you're working in js on a server, just a little more gymnastics goes a long way... Here's my ppos (pretty-print-on-server):

ppos = (object, space = 2) => JSON.stringify(object, null, space).split('\n').forEach(s => console.log(s));

which does a bang-up job of creating something I can actually read when I'm writing server code.

Solution 13 - Javascript

I don't know how it was never made officially, but I've added my own json method to console object for easier printing stringified logs:

> Observing Objects (non-primitives) in javascript is a bit like quantum mechanics..what you "measure" might not be the real state, which already have changed.

console.json = console.json || function(argument){
    for(var arg=0; arg < arguments.length; ++arg)
        console.log(  JSON.stringify(arguments[arg], null, 4)  )
}

// use example
console.json(   [1,'a', null, {a:1}], {a:[1,2]}    )

Many times it is needed to view a stringified version of an Object because printing it as-is (raw Object) will print a "live" version of the object which gets mutated as the program progresses, and will not mirror the state of the object at the logged point-of-time, for example:

var foo = {a:1, b:[1,2,3]}

// lets peek under the hood
console.log(foo) 

// program keeps doing things which affect the observed object
foo.a = 2
foo.b = null

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkizitView Question on Stackoverflow
Solution 1 - JavascriptcHaoView Answer on Stackoverflow
Solution 2 - JavascriptRoToRaView Answer on Stackoverflow
Solution 3 - JavascriptLukasz WiktorView Answer on Stackoverflow
Solution 4 - JavascriptDistdevView Answer on Stackoverflow
Solution 5 - JavascriptBERGUIGA Mohamed AmineView Answer on Stackoverflow
Solution 6 - JavascriptDave AndersonView Answer on Stackoverflow
Solution 7 - JavascriptmbenhalimaView Answer on Stackoverflow
Solution 8 - Javascriptdiego matos - kekeView Answer on Stackoverflow
Solution 9 - JavascriptRuwanthaView Answer on Stackoverflow
Solution 10 - JavascriptRayiezView Answer on Stackoverflow
Solution 11 - JavascriptKiran Kumar KotariView Answer on Stackoverflow
Solution 12 - JavascriptThe Software BarbarianView Answer on Stackoverflow
Solution 13 - JavascriptvsyncView Answer on Stackoverflow