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

如何用Python合并字段相似但数据不同的多个JSON对象?

解决方案

针对你的需求,我们可以通过分组相同字段行+收集差异字段并生成带序号的新字段来实现合并。以下是修改后的完整代码:

import csv
import json

def csv_to_json(csvFilePath, jsonFilePath):
    target_field = "Person Audience Type"
    grouped_data = {}

    # 读取CSV文件并分组
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
        
        for row in csvReader:
            # 生成分组键:排除目标字段,将剩余键值对转为排序后的元组(保证相同内容的行键一致)
            group_key = tuple(sorted((k, v) for k, v in row.items() if k != target_field))
            current_type = row[target_field]
            
            if group_key not in grouped_data:
                # 初始化分组:保留除目标字段外的所有数据,并用临时列表存差异值
                base_row = {k: v for k, v in row.items() if k != target_field}
                base_row['_temp_types'] = [current_type]
                grouped_data[group_key] = base_row
            else:
                # 追加差异字段值(如需去重可添加判断:if current_type not in ...)
                grouped_data[group_key]['_temp_types'].append(current_type)
    
    # 转换临时列表为带序号的字段
    jsonArray = []
    for item in grouped_data.values():
        type_list = item.pop('_temp_types')
        # 为每个差异值生成带序号的字段
        for idx, type_val in enumerate(type_list, start=1):
            item[f"{target_field}{idx}"] = type_val
        jsonArray.append(item)
    
    # 写入JSON文件
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)

csvFilePath = r'data.csv'
jsonFilePath = r'data.json'
csv_to_json(csvFilePath, jsonFilePath)

核心逻辑说明

  1. 分组依据:
    以除"Person Audience Type"外的所有字段组合作为分组键(转为排序后的元组确保键的唯一性和一致性),这样所有其他字段完全匹配的行会被分到同一组。

  2. 收集差异值:
    每个分组先保存基础数据(不含目标字段),再用临时列表收集该组内所有不同的"Person Audience Type"值。

  3. 生成带序号字段:
    遍历每个分组的临时列表,将值依次命名为Person Audience Type1、Person Audience Type2...并添加到基础数据中,最后移除临时列表字段,加入最终的JSON数组。

可选优化

如果需要对"Person Audience Type"的重复值去重,可将追加值的代码改为:

if current_type not in grouped_data[group_key]['_temp_types']:
    grouped_data[group_key]['_temp_types'].append(current_type)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:09:18