You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何将$.getJSON返回数据转换为可访问的字典或数组

代码问题分析
  • 遍历对象错误:urldata是接口返回的完整响应对象,使用for...in遍历得到的k是"data"、"draw"、"recordsTotal"这类字符串属性名,无法通过k[1]/k[2]取到城市、国家信息,目标数据实际存放在urldata.data数组中。
  • 遍历取值逻辑错误:即使遍历urldata.data数组,for...in遍历得到的k是索引字符串,需要通过urldata.data[k]才能拿到对应的城市子数组,直接取k的下标必然返回undefined。
  • 异步逻辑注意:$.getJSON是异步请求,所有需要使用最终数组的逻辑必须写在请求的回调函数内部,否则请求未完成时数组为空。
修复后实现代码
var arr = [];
$(document).ready(function(){
    $.getJSON('http://example.com/json.php',function(urldata){
        // 遍历存放城市数据的data数组
        urldata.data.forEach(item => {
            // item对应每个城市的子数组:[1, 'Tokyo', 'Japan', '83', '9', 0]
            const id = item[0];
            const city = item[1];
            const country = item[2];
            // 可选1:存为子数组格式,和你要求的表格结构一致
            arr.push([id, city, country]);
            // 可选2:存为对象格式,取值更便捷,推荐使用
            // arr.push({id: id, city: city, country: country});
            alert("City: " + city + " Country: " + country);
        })
        // 所有使用arr的逻辑请写在这里
        console.log(arr);
    });
})
结果说明
  • 如果选择子数组格式,最终arr结构如下:
[
  [1, "Tokyo", "Japan"],
  [2, "Paris", "France"],
  [3, "Rome", "Italy"]
]
  • 如果选择对象格式,最终arr结构如下,可通过arr[索引].city/arr[索引].country直接取值,使用更方便:
[
  {id: 1, city: "Tokyo", country: "Japan"},
  {id: 2, city: "Paris", country: "France"},
  {id: 3, city: "Rome", country: "Italy"}
]

内容的提问来源于stack exchange,提问作者Philippe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:54:00