如何从Spotify Web API中选择JSON响应中的数组

时间:2019-09-18 16:13:10

标签: node.js json api spotify

我需要将流派字段分配给一个新数组,但是我不确定如何只获取该字段或如何调用该字段

var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken('-----');

 spotifyApi.searchArtists('artist:queen')
   .then(function(data) {
     console.log('Search tracks by "queen" in the artist name', data.body.artists.items);
   }, function(err) {
     console.log('Something went wrong!', err);
   });

这是调用时的终端。 我只想要第一反应。

 PS C:\Users\g\Documents\js> node spotifyTest
Search tracks by "queen" in the artist name [ { external_urls:
     { spotify: 'https://open.spotify.com/artist/1dfeR4HaWDbWqFHLkxsg1d' },
    followers: { href: null, total: 19579534 },
    genres: [ 'glam rock', 'rock' ],
    href: 'https://api.spotify.com/v1/artists/1dfeR4HaWDbWqFHLkxsg1d',
    id: '1dfeR4HaWDbWqFHLkxsg1d',
    images: [ [Object], [Object], [Object], [Object] ],
    name: 'Queen',
    popularity: 90,
    type: 'artist',
    uri: 'spotify:artist:1dfeR4HaWDbWqFHLkxsg1d' },
  { external_urls:
     { spotify: 'https://open.spotify.com/artist/3nViOFa3kZW8OMSNOzwr98' },
    followers: { href: null, total: 1087117 },
    genres: [ 'deep pop r&b', 'pop', 'r&b' ],
    href: 'https://api.spotify.com/v1/artists/3nViOFa3kZW8OMSNOzwr98',
    id: '3nViOFa3kZW8OMSNOzwr98',
    images: [ [Object], [Object], [Object] ],
    name: 'Queen Naija',
    popularity: 68,
    type: 'artist',
    uri: 'spotify:artist:3nViOFa3kZW8OMSNOzwr98' } ]

1 个答案:

答案 0 :(得分:-1)

您可以使用点表示法访问JSON对象中的字段。这是一个用新数组替换第一响应类型的示例。

let responseItems = [ 
  { external_urls: { spotify: 'https://open.spotify.com/artist/1dfeR4HaWDbWqFHLkxsg1d' },
    followers: { href: null, total: 19579534 },
    genres: [ 'glam rock', 'rock' ],
    href: 'https://api.spotify.com/v1/artists/1dfeR4HaWDbWqFHLkxsg1d',
    id: '1dfeR4HaWDbWqFHLkxsg1d',
    images: [ [Object], [Object], [Object], [Object] ],
    name: 'Queen',
    popularity: 90,
    type: 'artist',
    uri: 'spotify:artist:1dfeR4HaWDbWqFHLkxsg1d' 
  },
  { 
    external_urls: { spotify: 'https://open.spotify.com/artist/3nViOFa3kZW8OMSNOzwr98' },
    followers: { href: null, total: 1087117 },
    genres: [ 'deep pop r&b', 'pop', 'r&b' ],
    href: 'https://api.spotify.com/v1/artists/3nViOFa3kZW8OMSNOzwr98',
    id: '3nViOFa3kZW8OMSNOzwr98',
    images: [ [Object], [Object], [Object] ],
    name: 'Queen Naija',
    popularity: 68,
    type: 'artist',
    uri: 'spotify:artist:3nViOFa3kZW8OMSNOzwr98' 
  } 
];
let firstResponse = responseItems[0];
console.log(JSON.stringify(firstResponse.genres, null, 2));
let newGenres = [ 'rock', 'jazz' ];
firstResponse.genres = newGenres;
console.log(JSON.stringify(firstResponse.genres, null, 2));

这应该在控制台中显示以下内容:

[
  "glam rock",
  "rock"
]

[
  "rock",
  "jazz"
]