如何从 spotify Web API 的 JSON 响应中挑选出一个数组



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

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:UsersgDocumentsjs> 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' } ]

您可以使用点表示法访问 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"
]

最新更新