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

Python多层字典键参数传递问题:合并JSON读写函数

问题描述

现有如下格式的JSON文件:

{
  "originProduct": {
      "statusType": "SALE",
      "saleType": "NEW",
      "leafCategoryId": "50002322",
      "name": "Jabra SPEAK 750 블루투스스피커/스피커폰/음성회의스피커폰/JABRA / 자브라 공식정품",
      "images": {
          "representativeImage": {
              "url": "http://shop1.phinf.naver.net/20221220_24/1671526069078ktTkT_JPEG/4172814067322311_1866531646.jpg"
          },
          "optionalImages": [
              {
                  "url": "http://shop1.phinf.naver.net/20221220_2/16715260691656YLKl_JPEG/4172814155176861_2054960625.jpg"
              },
              {
                  "url": "http://shop1.phinf.naver.net/20221220_5/1671526069249T4zWk_JPEG/4172814239069085_483270929.jpg"
              }
          ]
      }
}

已实现open、save和basic_data函数,其中basic_data负责加载JSON、生成基础数据并更新内容:

def open(self):
    with open(self.json_file,"r",encoding='utf-8-sig') as f:
        item_dic=json.load(f)
    return item_dic

def save(self,item_dic):
    with open(self.json_file,'w',encoding='utf-8-sig') as f:
        json.dump(item_dic,f,indent=4,ensure_ascii=False)

def basic_data(self):
    
    item_dic=self.open()

    statusType = "SALE" #상품상태
    saleType = "NEW" #판매유형
    leafCategoryId = self.soup()["category"]["categoryId"] #카테고리넘버
    name = self.soup()["name"] #상품명
    salePrice = self.soup()["salePrice"] #판매가
    stockQuantity = 100 #재고수량
    
    basic_data = {
        "statusType": statusType,
        "saleType": saleType,
        "leafCategoryId": leafCategoryId,
        "name": name,
        "salePrice": salePrice,
        "stockQuantity": stockQuantity,
    }
    try:
        del item_dic["originProduct"]["productLogistics"]
        del item_dic["originProduct"]["saleStartDate"]
        del item_dic["originProduct"]["saleEndDate"]
    except:
        pass
    item_dic["originProduct"].update(basic_data)
    self.save(item_dic)

现在要将open和save合并为save_func,初步实现如下:

def save_func(self,key,new_data):

## key -> parameter like ["originProduct"] ##

with open(self.json_file,"r",encoding='utf-8-sig') as f:
        item_dic=json.load(f)

item_dic.[key].update(basic_data)

with open(self.json_file,'w',encoding='utf-8-sig') as f:
        json.dump(item_dic,f,indent=4,ensure_ascii=False)

当前问题:传入单层key列表(如["originProduct"])时功能正常,但传入多层嵌套key列表(如["originProduct","images"])时,无法正确获取对应嵌套字典节点进行更新。

解决方案

要处理多层嵌套的key,需要通过遍历key列表逐步深入到目标字典节点,修改后的save_func实现如下:

import json

def save_func(self, key_list, new_data):
    # 读取JSON文件
    with open(self.json_file, "r", encoding='utf-8-sig') as f:
        item_dic = json.load(f)
    
    # 遍历key列表,定位目标嵌套字典
    target_node = item_dic
    for key in key_list:
        # 校验节点合法性,避免报错
        if isinstance(target_node, dict) and key in target_node:
            target_node = target_node[key]
        else:
            # 可根据业务需求调整错误处理逻辑,比如自动创建节点
            raise ValueError(f"嵌套路径 {key_list} 不存在或节点类型错误")
    
    # 更新目标节点数据
    target_node.update(new_data)
    
    # 保存修改后的JSON
    with open(self.json_file, 'w', encoding='utf-8-sig') as f:
        json.dump(item_dic, f, indent=4, ensure_ascii=False)

代码说明

  • 多层路径遍历:从根字典item_dic出发,依次用key列表中的每个元素向下定位,最终到达目标嵌套节点。
  • 合法性校验:每一步都检查当前节点是否为字典且存在对应key,避免运行时的KeyError或类型错误,可根据需求改成自动创建缺失的字典节点。
  • 数据更新:定位到目标节点后,调用update方法合并新数据。

使用示例

  • 更新单层节点:self.save_func(["originProduct"], basic_data)
  • 更新多层嵌套节点:比如要更新images下的内容,可传入["originProduct", "images"]和对应的新数据字典。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:40:44