import json from bcl_calculator import BCLDataSourceItem def process_project_data(json_data): """ 处理 projectData 中的线路特征段数据,计算每条 bpBillZhXsTable 记录的加权值, 并返回一个字典列表,每个字典包含 '特征段' 和对应的 ItemName: 计算结果。 :param json_data: 解析后的 JSON 数据(字典格式) :return: 字典列表,例如 [{"特征段": "1", "工地运输...": "21.8"}, ...] """ result_list = [] # 遍历每个线路特征段 for segment in json_data.get("projectData", {}).get("线路特征段", []): seg_name = segment.get("Name", "") # 提取特征段中的数字,例如 "特征段1" -> "1" seg_number = "".join(filter(str.isdigit, seg_name)) if not seg_number: seg_number = "0" # 默认值 # 获取 bpBillZhXsTable 列表 table_list = segment.get("bpBillZhXsTable", []) for item in table_list: try: # 提取字段并转换为浮点数 KnapScale = float(item.get("KnapScale", 0)) Knap = float(item.get("Knap", 0)) HillScale = float(item.get("HillScale", 0)) Hill = float(item.get("Hill", 0)) EdelweissScale = float(item.get("EdelweissScale", 0)) edelweiss = float(item.get("edelweiss", 0)) MountainScale = float(item.get("MountainScale", 0)) Mountain = float(item.get("Mountain", 0)) SloughScale = float(item.get("SloughScale", 0)) Slough = float(item.get("Slough", 0)) RiverScale = float(item.get("RiverScale", 0)) River = float(item.get("River", 0)) DesertScale = float(item.get("DesertScale", 0)) Desert = float(item.get("Desert", 0)) # 执行计算 total = ( (KnapScale * Knap) + (HillScale * Hill) + (EdelweissScale * edelweiss) + (MountainScale * Mountain) + (SloughScale * Slough) + (RiverScale * River) + (DesertScale * Desert) ) * 0.01 # 保留一位小数,格式化为字符串 calculated_value = f"{total:.1f}" # 获取 ItemName item_name = item.get("ItemName", "未知项目") # 构建结果字典 item_dict = {"特征段": seg_number, item_name: calculated_value} # 添加到结果列表 result_list.append(item_dict) except (ValueError, TypeError) as e: print(f"数据转换错误,跳过该项: {e}") continue return result_list # ============ 使用示例 ============ # 假设你已经通过 json.loads() 解析了你的 JSON 字符串 import json # 正确读取 JSON 文件的方式 with open("测试案例/主网预算线路.json", "r", encoding="utf-8") as file: data = json.load(file) # 调用函数处理数据 processed_data = process_project_data(data) # 现在 processed_data 是一个字典列表,你可以用它来创建 BCLDataSourceItem DXITEM = [BCLDataSourceItem(item) for item in processed_data] print(processed_data) print(DXITEM)