Print JSON parsed object?

2019-01-12 15:35发布

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?

11条回答
迷人小祖宗
2楼-- · 2019-01-12 16:16

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

console.dir(obj);

MDN says console.dir() is supported by:

  • FF8+
  • IE9+
  • Opera
  • Chrome
  • Safari
查看更多
We Are One
3楼-- · 2019-01-12 16:20

If you want to debug why not use console debug

window.console.debug(jsonObject);
查看更多
Animai°情兽
4楼-- · 2019-01-12 16:30

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
查看更多
干净又极端
5楼-- · 2019-01-12 16:32

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.

查看更多
Deceive 欺骗
6楼-- · 2019-01-12 16:33

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.

查看更多
ら.Afraid
7楼-- · 2019-01-12 16:36

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.

查看更多
登录 后发表回答