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

如何使用Terraform从嵌套API请求数据

解决方案

核心思路

通过逐层请求嵌套URL,依次获取三层JSON数据,再提取目标字段并整合为指定格式的映射。以下用Python实现完整流程:


步骤1:准备依赖

先安装HTTP请求库:

pip install requests

步骤2:编写JSON请求工具函数

封装通用的JSON请求逻辑,处理网络请求异常:

import requests

def fetch_json(url):
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()  # 抛出HTTP错误
        return response.json()
    except Exception as e:
        print(f"请求URL失败 {url}: {str(e)}")
        return None

步骤3:逐层提取并整合数据

假设第一层JSON是包含多个对象的列表,每个对象的第一个键对应第二层URL;第二层JSON同理指向第三层URL。根据实际结构调整字段名:

def extract_nested_data(first_layer_url):
    # 1. 获取第一层JSON数据
    first_data = fetch_json(first_layer_url)
    if not first_data:
        return []
    
    result = []
    for item in first_data:
        # 2. 获取第二层URL(取当前对象的第一个键对应的值)
        second_layer_url = next(iter(item.values()))
        second_data = fetch_json(second_layer_url)
        if not second_data:
            continue
        
        # 3. 获取第三层URL(同理取第二层对象的第一个键对应的值)
        third_layer_url = next(iter(second_data.values()))
        third_data = fetch_json(third_layer_url)
        if not third_data:
            continue
        
        # 4. 提取目标字段(根据实际JSON结构调整键名)
        mapped_item = {
            "url": third_layer_url,  # 或你需要的对应URL字段
            "apn": third_data.get("apn"),
            "operator": third_data.get("operator"),
            "iprange": third_data.get("iprange"),
            "network": third_data.get("network")
        }
        result.append(mapped_item)
    
    return result

# 调用示例
first_url = "你的第一层JSON URL"
final_mappings = extract_nested_data(first_url)

# 按指定格式输出结果
for idx, mapping in enumerate(final_mappings):
    print(f"--- 条目 {idx+1} ---")
    print(f"url = {mapping['url']}")
    print(f"apn = {mapping['apn']}")
    print(f"operator = {mapping['operator']}")
    print(f"iprange = {mapping['iprange']}")
    print(f"network = {mapping['network']}\n")

关键说明

  • 如果JSON结构不是“对象第一个键为URL”,需根据实际返回的JSON结构修改提取URL的逻辑,比如指定固定键名而非next(iter(item.values()))。
  • 异常处理可避免单个URL请求失败导致整个流程中断。
  • 最终的final_mappings是整合后的数据集,可直接用于按network筛选等后续操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:35:03