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

Python解析含重复键的JSON并汇总相同键值的方法求助

解决JSON属性汇总问题的分步指南

Hey there! Let's work through this problem together—sounds like you're already off to a good start loading the JSON file, so we'll focus on fixing the features access issue and building the sum logic.

第一步:确保正确访问features字段

First, let's make sure you can reliably get the features list from your JSON data. Sometimes KeyErrors happen if the key is misspelled, or if the JSON structure isn't what you expect. Try this approach to avoid crashes and debug the structure:

import json

# 加载你的JSON文件
with open("your_input.json", "r") as input_file:
    data = json.load(input_file)

# 安全获取features列表(如果键不存在则返回空列表)
features = data.get("features", [])

# 调试:检查features是否存在,并打印第一个条目查看结构
if not features:
    print("警告:JSON文件中未找到'features'!请检查结构是否正确。")
else:
    # 打印第一个feature,确认目标属性的位置
    print(json.dumps(features[0], indent=4))

运行这段代码后,你就能清楚看到每个feature的结构——这类JSON里目标属性(比如p_30_34_yrs)通常嵌套在properties键下(GeoJSON常用这个结构),你可以根据打印结果调整后续代码的路径。

第二步:汇总目标属性的数值

确认结构后,我们来编写累加逻辑:初始化一个汇总字典,遍历每个feature并累加指定属性的数值:

# 定义需要汇总的属性列表
target_attrs = ["p_30_34_yrs", "p_tot"]

# 为每个目标属性初始化累加值为0
summary = {attr: 0 for attr in target_attrs}

# 遍历每个feature,累加数值
for feature in features:
    # 获取properties(如果你的属性直接在feature里,就把这行改成props = feature)
    props = feature.get("properties", {})
    
    for attr in target_attrs:
        # 仅当属性存在且为数值类型时累加(避免报错)
        if attr in props and isinstance(props[attr], (int, float)):
            summary[attr] += props[attr]
        # 可选:处理字符串格式的数值(如果你的JSON里有这种情况)
        elif attr in props and isinstance(props[attr], str):
            try:
                summary[attr] += float(props[attr])
            except ValueError:
                print(f"跳过{attr}的非数值内容:{props[attr]}")

第三步:输出汇总结果到JSON文件

最后,把汇总后的字典写入新的JSON文件:

# 将汇总结果保存到新的JSON文件
with open("summary_output.json", "w") as output_file:
    json.dump(summary, output_file, indent=4)

print(f"汇总完成!结果已保存到summary_output.json:\n{summary}")

针对你的JSON结构的调整提示:

  • 路径修改:如果目标属性不在properties下,把feature.get("properties", {})改成feature(或者对应嵌套的键名)。
  • 动态匹配属性:如果你想汇总所有以p_开头的属性(不用手动列举),可以替换成这段代码:
    summary = {}
    for feature in features:
        props = feature.get("properties", {})
        for key, value in props.items():
            if key.startswith("p_") and isinstance(value, (int, float)):
                summary[key] = summary.get(key, 0) + value
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:38:16