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

嵌套JSON数据与Excel列对比的Python实现方案咨询

优化JSON参数提取与Excel列匹配对比方案

问题背景

现有嵌套结构的JSON数据(包含Services、RoadAttributes、egoInformation等层级),需要与指定Excel列进行参数匹配对比。已尝试Python代码读取JSON,但无法高效提取参数,需求优化的参数提取及对比实现方法。

相关资源

JSON结构示例

{
  "Services": {
    "RoadAttributes": {
      "egoInformation": [
        {
          "roundabout": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "tollStation": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "railroadcrossing": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "speedbump": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "tunnel": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "urbanArea": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "streetClass": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "functionalRoadClass": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "constructionSite": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "laneIndexEgo": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "laneNumbers": {
            "id": 5,
            "value1": 5,
            "value2": 5,
            "source": 5
          },
          "laneAcceleration": {
            "id": 5,
            "value1": 5,
            "value2": 5,
            "source": 5
          },
          "laneDeceleration": {
            "id": 5,
            "value1": 5,
            "value2": 5,
            "value3": 5,
            "source": 5
          },
          "laneWidth": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "structuralSeperation": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "ramp": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "insideCity": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "crosswalk": {
            "id": 5,
            "value1": 5,
            "source": 5
          },
          "intersection": {
            "id": 5,
            "value1": 5,
            "value2": 5,
            "source": 5
          },
          "relativeYawAngle": 5,
          "messageCounter": 4
        }
      ]
    }
  }
}

Excel列说明

Excel列包含以下字段(对应JSON中的参数):roundabout、tollStation、railroadcrossing、speedbump、tunnel、urbanArea、streetClass、functionalRoadClass、constructionSite、laneIndexEgo、laneNumbers、laneAcceleration、laneDeceleration、laneWidth、structuralSeperation、ramp、insideCity、crosswalk、intersection、relativeYawAngle、messageCounter,每个字段对应需要匹配的参数值。

原测试代码

import json
import json as js

# Read the JSON file
with open("ampmin.json") as f:
    data = js.load(f)

# Temp_Data=data['Services']
# print(Temp_Data)
for d in data:
    Temp_Data = d['Services']

优化实现方案

1. 高效提取JSON参数

原代码遍历data的方式错误,因为data是字典而非列表,直接通过键层级访问即可提取目标数据。可以将嵌套参数扁平化,生成便于对比的键值对字典:

import json

def flatten_ego_info(ego_data):
    flattened = {}
    for key, value in ego_data.items():
        if isinstance(value, dict):
            # 提取嵌套字典中的核心字段,可根据Excel需求调整
            flattened[f"{key}_id"] = value.get("id")
            flattened[f"{key}_value1"] = value.get("value1")
            flattened[f"{key}_source"] = value.get("source")
            # 处理含value2、value3的特殊字段
            if "value2" in value:
                flattened[f"{key}_value2"] = value["value2"]
            if "value3" in value:
                flattened[f"{key}_value3"] = value["value3"]
        else:
            # 直接值类型字段直接存入
            flattened[key] = value
    return flattened

# 读取JSON文件
with open("ampmin.json") as f:
    data = json.load(f)

# 提取egoInformation中的目标数据(若列表有多元素可遍历处理)
ego_info = data["Services"]["RoadAttributes"]["egoInformation"][0]
flattened_params = flatten_ego_info(ego_info)

2. 读取Excel并匹配对比

使用pandas库读取Excel,将提取的JSON参数与Excel列进行匹配,输出对比结果:

import pandas as pd

# 读取Excel文件,假设第一行为列名
df = pd.read_excel("road_params.xlsx")

# 取Excel第一行作为对比示例(需批量对比可遍历df各行)
excel_row = df.iloc[0].to_dict()

# 执行参数对比
comparison_result = {}
for param in flattened_params:
    # 建立JSON参数与Excel列名的映射关系,可根据实际情况调整
    excel_key = param.split("_")[0] if "_" in param else param
    if excel_key in excel_row:
        comparison_result[param] = {
            "json_value": flattened_params[param],
            "excel_value": excel_row[excel_key],
            "match": flattened_params[param] == excel_row[excel_key]
        }

# 输出对比结果
for param, result in comparison_result.items():
    status = "一致" if result["match"] else "不一致"
    print(f"参数{param}: JSON值={result['json_value']}, Excel值={result['excel_value']}, 匹配状态={status}")

关键说明

  • 扁平化JSON时,可根据Excel实际需要的字段调整提取逻辑;
  • Excel列名与JSON参数的映射关系需根据实际场景适配,若Excel列包含后缀(如roundabout_value1),可直接对应;
  • 若egoInformation是多元素列表,需遍历列表元素实现批量对比。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:57:09