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

How do I convert a remote JSON object to an Array in JavaScript

我正在尝试从我的 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 方法 spread 不起作用,因为它仅适用于数组。

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

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;}