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

如何在Python中重组JSON字符串并去除冗余元素

如何将Pandas DataFrame转换为嵌套结构的JSON?

你可以通过两种方式实现需求:直接操作原始DataFrame(更高效),或者处理已有的JSON字符串。

方法一:直接从Pandas DataFrame转换

利用groupby分组共同字段,再将每组的指定列打包成嵌套的Results数组:

import pandas as pd

# 构建原始DataFrame(如果已有可直接使用)
data = {
    "ID": [1, 2],
    "Salary1": [69.43, 691.43],
    "Salary2": [513.0, 5123.0],
    "Date": ["2022-06-09", "2022-06-09"],
    "Name": ["john", "john"],
    "employeeId": [12, 12],
    "DateTime": ["2022-09-0710:57:55", "2022-09-0710:57:55"]
}
df = pd.DataFrame(data)

# 调整数据类型匹配目标格式:Salary2转整数,ID转整数(按需调整)
df["Salary2"] = df["Salary2"].astype(int)
df["ID"] = df["ID"].astype(int)

# 分组并构造嵌套结构
grouped_df = df.groupby(
    ["Date", "Name", "DateTime", "employeeId"], 
    as_index=False
).apply(
    lambda group: group[["ID", "Salary1", "Salary2"]].to_dict("records")
).rename("Results")

# 转换为目标JSON格式
target_json = grouped_df.to_json(orient="records", indent=3)
print(target_json)

运行后会输出你需要的嵌套结构JSON。

方法二:处理已有的JSON字符串

如果已经有转换好的JSON字符串,可通过字典分组实现嵌套:

import json

# 原始JSON字符串
original_json = '''
[
   {
      "ID":"1",
      "Salary1":69.43,
      "Salary2":513.0,
      "Date":"2022-06-09",
      "Name":"john",
      "employeeId":12,
      "DateTime":"2022-09-0710:57:55"
   },
   {
      "ID":"2",
      "Salary1":691.43,
      "Salary2":5123.0,
      "Date":"2022-06-09",
      "Name":"john",
      "employeeId":12,
      "DateTime":"2022-09-0710:57:55"
   }
]
'''

# 解析JSON为列表
data_items = json.loads(original_json)

# 按共同字段分组,构造嵌套结构
group_keys = ("Date", "Name", "DateTime", "employeeId")
result_dict = {}

for item in data_items:
    # 用共同字段的元组作为分组键
    group_key = tuple(item[key] for key in group_keys)
    # 整理结果项(按需调整数据类型)
    result_item = {
        "ID": int(item["ID"]) if item["ID"].isdigit() else item["ID"],
        "Salary1": item["Salary1"],
        "Salary2": int(item["Salary2"])
    }
    
    if group_key not in result_dict:
        # 初始化分组条目
        result_dict[group_key] = {key: item[key] for key in group_keys}
        result_dict[group_key]["Results"] = []
    result_dict[group_key]["Results"].append(result_item)

# 转换为最终JSON
target_json = json.dumps(list(result_dict.values()), indent=3)
print(target_json)

注意事项

  • 目标格式中ID既有整数又有字符串,若需要统一类型,可去掉int()转换或全部转为字符串;
  • Salary2转换为整数是为了匹配目标里的非浮点数格式,若不需要可跳过类型转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:21:17