You need to enable JavaScript to run this app. Python如何为批量抓取的JSON数组元素添加对应来源站点顶层键
优惠活动
大模型
产品
解决方案
定价
更多

Python如何为批量抓取的JSON数组元素添加对应来源站点顶层键

站点标识绑定调整方案

1. 前置配置改造:从源头绑定站点与接口映射

移除仅存储接口地址的无关联列表,改为结构化配置,每个条目直接关联站点名与对应接口地址,避免请求完成后丢失来源对应关系。
示例配置:

# 原无标识的接口列表
# api_urls = [
#     "https://api.site1.com",
#     "https://api.site2.com",
#     "https://api.site3.com"
# ]

# 改造后的带映射关系的配置
api_config = [
    {"site_name": "资讯站点", "api_url": "https://api.site1.com"},
    {"site_name": "电商站点", "api_url": "https://api.site2.com"},
    {"site_name": "社区站点", "api_url": "https://api.site3.com"},
]

2. 抓取环节直接组装目标嵌套结构

遍历配置发请求时,不直接将接口返回的原始JSON存入总列表,直接按需求组装为「站点名-返回数据」的嵌套键值对,无需后续额外加工。
核心抓取逻辑:

import requests
import json

final_result = []
for config_item in api_config:
    resp = requests.get(config_item["api_url"], timeout=10)
    resp.raise_for_status()
    origin_data = resp.json()
    # 组装为目标结构
    final_result.append({
        config_item["site_name"]: origin_data
    })

3. 序列化写入保持原有格式化要求

原有json.dump的sort_keys、indent格式化参数保留,可额外添加ensure_ascii=False参数,避免中文站点名出现Unicode转义乱码:

with open("data.json", "w", encoding="utf-8") as f:
    json.dump(
        final_result,
        f,
        sort_keys=True,
        indent=2,
        ensure_ascii=False
    )

最终输出JSON结构示例

[
  {
    "资讯站点": {
      "total": 10,
      "list": ["新闻条目1", "新闻条目2"]
    }
  },
  {
    "电商站点": {
      "total": 20,
      "goods": ["商品1", "商品2"]
    }
  },
  {
    "社区站点": {
      "total": 30,
      "posts": ["帖子1", "帖子2"]
    }
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 05:15:04