You need to enable JavaScript to run this app. 如何处理巴西银行API返回JSON中键统一为nomeBeneficio的多字典条目?
优惠活动
大模型
产品
解决方案
定价
更多

如何处理巴西银行API返回JSON中键统一为nomeBeneficio的多字典条目?

解决方案:修复异常JSON并提取目标数据

针对你从巴西银行API获取的JSON异常(所有城市条目共用nomeBeneficio键),以下是两种实用处理方案:

1. 提取结构化城市数据(转为Polars DataFrame)

该方案将分散的城市数据提取并拆分为月份、城市名、州缩写的结构化格式,方便后续数据分析或存储:

import json
import polars as pl

# 读取原始JSON文件
with open(r"C:\Users\Henrique RIbeiro\Documents\projetos em andamentos\daf extração\daf_extractions\json4\renomeados\ABAIRA_dados_anuais.json", "r", encoding="utf-8") as file:
    raw_data = json.load(file)

months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
processed_records = []

for month in months:
    if month not in raw_data:
        continue
    
    skip_flag = False
    for entry in raw_data[month]['quantidadeOcorrencia']:
        full_name = entry.get('nomeBeneficio', '').strip()
        if not full_name:
            continue
        # 跳过总计行,只提取之后的城市数据
        if full_name == "TOTAL POR PARCELA / NATUREZA":
            skip_flag = True
            continue
        if skip_flag:
            # 拆分城市名与州缩写(格式:城市名 -州)
            city_name, state_code = full_name.rsplit("-", 1)
            processed_records.append({
                "month": month,
                "city": city_name.strip(),
                "state": state_code.strip()
            })

# 转为Polars DataFrame
result_df = pl.DataFrame(processed_records)
print(result_df.head())
# 保存为CSV格式(也可改用write_parquet)
result_df.write_csv("structured_city_data.csv", encoding="utf-8")

2. 重新格式化JSON结构

如果需要保留JSON格式,可将原异常结构修复为更清晰的层级,把重复键的城市条目整理为统一列表:

import json

# 读取原始JSON文件
with open(r"C:\Users\Henrique RIbeiro\Documents\projetos em andamentos\daf extração\daf_extractions\json4\renomeados\ABAIRA_dados_anuais.json", "r", encoding="utf-8") as file:
    raw_data = json.load(file)

months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
formatted_data = {}

for month in months:
    if month not in raw_data:
        continue
    
    skip_flag = False
    city_list = []
    for entry in raw_data[month]['quantidadeOcorrencia']:
        full_name = entry.get('nomeBeneficio', '').strip()
        if not full_name:
            continue
        if full_name == "TOTAL POR PARCELA / NATUREZA":
            skip_flag = True
            continue
        if skip_flag:
            city_list.append(full_name)
    
    # 重构月份下的结构
    formatted_data[month] = {
        "total_benefits": raw_data[month]['quantidadeBeneficio'],
        "continue_search": raw_data[month]['indicadorContinuarPesquisa'],
        "cities": city_list
    }

# 保存格式化后的JSON
with open("formatted_city_data.json", "w", encoding="utf-8") as output_file:
    json.dump(formatted_data, output_file, ensure_ascii=False, indent=2)

说明

  • 两个方案都会自动跳过TOTAL POR PARCELA / NATUREZA行,只提取有效城市数据
  • 结构化方案拆分了城市与州信息,适合后续统计分析;格式化方案保留JSON层级,方便API复用或数据归档

内容的提问来源于stack exchange,提问作者Henrique R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:47:01