如何在 JavaScript 中将远程 JSON 对象转换为数组



我正在尝试从我的 Icecast 服务器中获取 JSON 对象并将其转换为数组,以便我可以访问当前的侦听器数量统计信息并将其显示在 html 中。

这是我的JS:

const endpoint = 'http://stream.8k.nz:8000/status-json.xsl';    
const serverStats = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => serverStats.push(data));

这只是将对象添加为数组中的单个项目。ES6 方法扩展不起作用,因为它仅适用于数组。

不需要数组。您只接收一个对象,并且可以从该对象轻松访问所需的属性

const endpoint = 'http://stream.8k.nz:8000/status-json.xsl';    
const serverStats = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data =>{
let source = data.icestats.source;
// console.log(source)
console.log('Listeners =', source.listeners, ' Peak=', source.listener_peak)
console.log('n ******************* n')
// to iterate over all the source key/values
Object.keys(source).forEach(k=> console.log(k,'=', source[k]))

})
.as-console-wrapper {	max-height: 100%!important;}

最新更新