console.log为某些字段返回“对象”,而不是正文数据[spotify-web-api-node]

问题描述

我正在使用spotify-web-api-node,当我进行api调用时,返回的数据看起来像在控制台中一样:

Album information {
  album_type: 'album',artists: [
    {
      external_urls: [Object],href: 'https://api.spotify.com/v1/artists/2hazSY4Ef3aB9ATXW7F5w3',id: '2hazSY4Ef3aB9ATXW7F5w3',name: 'IZAL',type: 'artist',uri: 'spotify:artist:2hazSY4Ef3aB9ATXW7F5w3'
    }
  ],...

  label: 'Hook Ediciones Musicales',name: 'Agujeros de Gusano',popularity: 0,release_date: '2014-01-25',release_date_precision: 'day',total_tracks: 13,tracks: {
offset=0&limit=50',items: [
      [Object],[Object],[Object]
    ],limit: 50,next: null,offset: 0,prevIoUs: null,total: 13
  },type: 'album',uri: 'spotify:album:5U4W9E5WsYb2jUQWePT8Xm'
}

如您所见,某些字段,例如external_urls:和(以后)items:返回了[Object],而不是实际数据。 该特定示例的(node.js)代码如下:

spotifyApi.getAlbum('5U4W9E5WsYb2jUQWePT8Xm')
  .then(function(data) {
    console.log('Album information',data.body);
  },function(err) {
    console.error(err);
});

如果我将data.body中的console.log部分更改为JSON.stringify(data.body),那会更好一些,因为它确实返回了数据,但返回的是字符串(显然),这并不完全正确。可用:

Album information {"album_type":"album","artists":[{"external_urls":{"spotify":"https://open.spotify.com/artist/2hazSY4Ef3aB9ATXW7F5w3"},"href":"https://api.spotify.com/v1/artists/2hazSY4Ef3aB9ATXW7F5w3","id":"2hazSY4Ef3aB9ATXW7F5w3","name":"IZAL","type":"artist","uri":"spotify:artist:2hazSY4Ef3aB9ATXW7F5w3"}],"available_markets":[],"copyrights":[{"text":"2013 Hook Ediciones Musicales","type":"C"},{"text":"2013 Hook Ediciones Musicales","type":"P"}],

等。也尝试了JSON.parse(JSON.stringify(data.body)),但得到的输出console.log相同。

如何获取字段的实际数据而不丢失其格式?

解决方法

您可以使用console.log(JSON.stringify(data.body,null,2))

这会在树中打印JSON,而不会像在[Object]中看到的那样丢失其内容。

,

在@snak的评论之后,我将console.log行更改为:

console.log('Album information',util.inspect(data.body,false,true));

似乎返回的一切都很好,没有[Object]

(确保包括const util = require('util');并与npm install util --save一起安装。)