为什么在node.js中打印到控制台而不是对象的内容?

我试图访问由spotify API返回的播放列表对象中的每首歌曲。 当我得到JSON对象时,它会在“项目”中返回一堆[Object]的东西,这些东西就是轨道所在的位置:

spotifyApi.getPlaylist(id, listID) .then(function (data) { // printing data from this line console.log('The playlist contains these tracks', data.body); }, function (err) { console.log('Something went wrong!', err); }); 

输出:

 Playlist name : thug lif3 Playlist ID: 41moBc7H5bWrR3iiY0Zu9Q The playlist contains these tracks { /*~~~ lots of skipped output ~~~*/ { href: 'https://api.spotify.com/v1/users/...', /*~~~ why [Object]? ~~~*/ items: [ [Object], [Object], [Object] ], limit: 100 }, } 

这些[对象]事物是无效的标志,还是有某种方法可以parsing它们并从中获取数据? Spotify网站上的API浏览器显示“Items”后的实际轨迹对象,所以我很困惑为什么我的应用程序请求不一样。

你可以有console.log输出正确的JSON:

 console.log('The playlist contains these tracks %j', data.body); 

%jlogging在这里 )。

console.log为对象生成的常规输出不是正确的JSON,也限制在某个对象深度; 之后,你会得到[Object]string。

这就是多深嵌套的对象被打印到节点的控制台。 他们仍然可用编程。 在你的情况下,使用data.body.tracks.items来访问对象。

如果你想要一个漂亮的打印机,你可以使用bunyan ,这将使嵌套对象(和其他所有东西)在控制台中看起来非常好。

这是节点的正常行为。 以编程方式向下钻取或使用util.inspect 链接

这应该做的伎俩:

 var util = require('util'); ... spotifyApi.getPlaylist(id, listID) .then(function (data) { // printing data from this line console.log('The playlist contains these tracks', util.inspect(data.body, { showHidden: true, depth: null }); }, function (err) { console.log('Something went wrong!', err); });