You need to enable JavaScript to run this app. Python解析JSON转字典时otherList键值覆盖、x字段缺失的问题解决
优惠活动
大模型
产品
解决方案
定价
更多

Python解析JSON转字典时otherList键值覆盖、x字段缺失的问题解决

问题根因
  • 键值覆盖逻辑错误:生成otherList_*系列键时,仅使用内层otherList的遍历序号作为键后缀,未区分字段所属的List1子项,导致遍历第二个List1子项(P2)时,生成的otherList_id_n1、otherList_id_n2等键与第一个子项(P1)的对应键完全重名,新值直接覆盖旧值,最终丢失P1对应的otherList数据。
  • 缺失字段写入:代码未将每个List1子项包含的x字段写入目标字典,最终输出缺少对应值。
  • 字典实例复用问题:代码仅在全局初始化一次空字典,逐行解析JSON时未重置字典内容,后续行的解析会与前一行数据发生串扰。
  • 期望输出的逻辑矛盾:你提供的期望输出包含两组完全重名的otherList_*n1*、otherList_*n2*键,而Python字典的键要求全局唯一,相同键多次赋值只会保留最后一次写入的值,无法同时存储两个子项的同序号otherList内容,必须给键名加上所属List1子项的层级标识才能实现完整存储。
修正实现方案
  • 逐行解析JSON前,先初始化空字典,避免跨行数据串扰
  • 生成otherList_*系列键时,拼接当前List1子项的层级序号,避免键名冲突
  • 显式将每个List1子项的x字段写入结果字典
  • 用上下文管理器管理文件打开操作,避免文件句柄泄漏

修正后的可运行代码:

import json

data_file = "inp2.json"
# 用上下文管理器自动管理文件句柄
with open(data_file, 'r', encoding='utf-8') as file:
    for line in file:
        # 每行解析前重置空字典,避免跨行数据串扰
        dict1 = {}
        json_line = json.loads(line.strip())
        dict1["id"] = json_line["id"]
        json_list1 = json_line["List1"]
        for i, sub_item in enumerate(json_list1):
            i_val = i + 1
            dict1[f"sub_n{i_val}"] = sub_item['sub']
            dict1[f"subReport_a_n{i_val}"] = sub_item['subReport']['a']
            dict1[f"subReport_b_n{i_val}"] = sub_item['subReport']['b']
            # 写入缺失的x字段
            dict1[f"x_n{i_val}"] = sub_item['x']
            # 遍历当前子项的otherList,键名携带子项层级标识,避免键名冲突
            for j, other_item in enumerate(sub_item['otherList']):
                n_val = j + 1
                key_prefix = f"otherList_sub{i_val}_n{n_val}"
                dict1[f"{key_prefix}_id"] = other_item['id']
                dict1[f"{key_prefix}_a"] = other_item['other_rep']['a']
                dict1[f"{key_prefix}_b"] = other_item['other_rep']['b']
        print("dict:", dict1)

修正后对id=101行的解析输出为:

dict: {'id': 101, 'sub_n1': 'P1', 'subReport_a_n1': 74, 'subReport_b_n1': 65, 'x_n1': 322, 'otherList_sub1_n1_id': 5, 'otherList_sub1_n1_a': 67, 'otherList_sub1_n1_b': 65, 'otherList_sub1_n2_id': 6, 'otherList_sub1_n2_a': 66, 'otherList_sub1_n2_b': 65, 'sub_n2': 'P2', 'subReport_a_n2': 86, 'subReport_b_n2': 65, 'x_n2': 59, 'otherList_sub2_n1_id': 7, 'otherList_sub2_n1_a': 65, 'otherList_sub2_n1_b': 65, 'otherList_sub2_n2_id': 2, 'otherList_sub2_n2_a': 64, 'otherList_sub2_n2_b': 65}

如果要实现你最初设想的“每个子项的otherList从n1开始计数、按子项顺序依次存储”的效果,需要切换为支持重复键的存储结构(比如有序列表按顺序记录键值对),普通Python字典无法实现该需求,键唯一性是字典的固有特性。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 16:24:03