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

如何遍历JSON数组?附从URL加载的JSON文件示例

嘿,很高兴能帮你解决这两个技术问题!下面分情况给你详细说明:

问题1:如何遍历JSON数组?

JSON数组本质是有序的元素集合,遍历的核心是先将JSON字符串解析成对应编程语言的数组/列表结构,再通过循环访问每个元素。以下是两种常用语言的实现示例:

JavaScript 示例

假设你已经将JSON解析为JS数组(如果是从URL加载的字符串,先用JSON.parse()转换),可以用多种方式遍历:

// 解析后的Airports数组
const airports = [
  { "listing": "East 34th Street Heliport", "iata": "TSS", "type": "heliport", "size": "tiny" },
  { "listing": "Blaine Municipal Airport", "iata": "BWS", "type": "closed", "size": "small" }
];

// 方式1:forEach 方法(最简洁)
airports.forEach(airport => {
  console.log(`机场名称:${airport.listing},IATA代码:${airport.iata}`);
});

// 方式2:for...of 循环(适合需要中断循环的场景)
for (const airport of airports) {
  if (airport.type === "closed") {
    console.log(`已关闭机场:${airport.listing}`);
    break; // 找到第一个关闭的机场就停止遍历
  }
}

// 方式3:传统for循环(需要索引时使用)
for (let i = 0; i < airports.length; i++) {
  console.log(`第${i+1}个机场:${airports[i].listing}`);
}

Python 示例

用json模块将JSON字符串解析为Python列表后,直接循环即可:

import json

# 解析后的Airports列表
airports = [
  {"listing": "East 34th Street Heliport", "iata": "TSS", "type": "heliport", "size": "tiny"},
  {"listing": "Blaine Municipal Airport", "iata": "BWS", "type": "closed", "size": "small"}
]

# 方式1:普通for循环(最常用)
for airport in airports:
    print(f"机场名称:{airport['listing']},类型:{airport['type']}")

# 方式2:列表推导式(快速提取特定字段)
all_iata_codes = [airport['iata'] for airport in airports]
print("所有机场IATA代码:", all_iata_codes)
问题2:从URL加载并处理你的Airports JSON文件

从URL加载JSON的关键是先发起网络请求获取JSON字符串,再解析为对应语言的数据结构,最后遍历Airports数组。以下是具体实现:

JavaScript(浏览器环境)

使用浏览器内置的fetch API完成请求和解析:

// 替换为你的JSON文件实际URL
const jsonUrl = "https://example.com/your-airports.json";

fetch(jsonUrl)
  .then(response => {
    if (!response.ok) {
      throw new Error(`请求失败:${response.status}`);
    }
    return response.json(); // 将响应解析为JS对象
  })
  .then(data => {
    // 获取顶层的Airports数组
    const airports = data.Airports;
    
    // 遍历数组并处理数据
    airports.forEach(airport => {
      console.log(`${airport.listing} (${airport.iata}) - 规模:${airport.size}`);
    });
  })
  .catch(error => {
    console.error("加载或解析JSON出错:", error);
  });

Python 示例

使用requests库(需先通过pip install requests安装)发起请求:

import json
import requests

# 替换为你的JSON文件实际URL
json_url = "https://example.com/your-airports.json"

try:
    # 发送GET请求获取JSON数据
    response = requests.get(json_url)
    response.raise_for_status()  # 如果请求失败(如404、500),抛出异常
    
    # 将响应内容解析为Python字典
    data = response.json()
    
    # 遍历Airports数组
    for airport in data['Airports']:
        print(f"{airport['listing']} ({airport['iata']}) - 类型:{airport['type']}")
        
except requests.exceptions.RequestException as e:
    print(f"网络请求出错:{e}")
except json.JSONDecodeError:
    print("JSON格式无效,解析失败")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 07:04:09