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

如何更新JSON中特定slot区块的指定键值对

如何更新JSON中指定Slot区块的键值?

需求场景

需要更新如下JSON字符串中指定slot(如slot1)内的对应键值:

{
  "slot1": {"name":"","head":0,"face":0,"body":0,"neck":0,"hand":0,"feet":0,"color":0},
  "slot2": {"name":"","head":0,"face":0,"body":0,"neck":0,"hand":0,"feet":0,"color":0},
  "slot3": {"name":"","head":0,"face":0,"body":0,"neck":0,"hand":0,"feet":0,"color":0},
  "slot4": {"name":"","head":0,"face":0,"body":0,"neck":0,"hand":0,"feet":0,"color":0},
  "slot5": {"name":"","head":0,"face":0,"body":0,"neck":0,"hand":0,"feet":0,"color":0},
  "slot6": {"name":"","head":0,"face":0,"body":0,"neck":0,"hand":0,"feet":0,"color":0}
}

已有从客户端获取参数的异步处理函数,需补充更新逻辑:

@handlers.handler(XTPacket('outfit', 'save'))
@handlers.cooldown(1)
async def handle_outfit_save(self, p, outfitName: str, slot_id: int, colour_id: int, head: int, face: int, neck: int, body: int, hand: int, feet: int):
    # self.outfits 存储上述JSON字符串
    # slot_id 返回1-6的数字,需拼接为"slot + slot_id"形式
    print("Current Slot Name: " + outfitName)
    print("Current Slot Saved: " + slot_id)

实现步骤

  1. 解析JSON字符串为Python字典:用json.loads把存储的JSON字符串转成可直接操作的字典结构。
  2. 拼接目标Slot键名:将slot_id转为字符串后拼接成slotX格式的键名。
  3. 更新指定Slot的键值:通过字典索引直接修改对应Slot内的各个字段值。
  4. 转回JSON字符串并保存:用json.dumps把更新后的字典重新序列化为JSON字符串,存回self.outfits。

完整修改后的代码

import json

@handlers.handler(XTPacket('outfit', 'save'))
@handlers.cooldown(1)
async def handle_outfit_save(self, p, outfitName: str, slot_id: int, colour_id: int, head: int, face: int, neck: int, body: int, hand: int, feet: int):
    # 1. 解析JSON为字典
    outfits_dict = json.loads(self.outfits)
    
    # 2. 拼接目标slot的键名
    target_slot = f"slot{slot_id}"
    
    # 3. 更新对应slot的所有字段(先检查slot是否存在,避免KeyError)
    if target_slot in outfits_dict:
        outfits_dict[target_slot] = {
            "name": outfitName,
            "head": head,
            "face": face,
            "body": body,
            "neck": neck,
            "hand": hand,
            "feet": feet,
            "color": colour_id
        }
    
    # 4. 转回JSON字符串并保存
    self.outfits = json.dumps(outfits_dict)
    
    # 修正print的类型问题(int不能直接和str拼接)
    print("Current Slot Name: " + outfitName)
    print("Current Slot Saved: " + str(slot_id))

注意事项

  • 必须先导入json模块,确保JSON解析和序列化功能正常。
  • 增加了target_slot存在性检查,防止非法slot_id导致的报错。
  • 原代码中print("Current Slot Saved: " + slot_id)会触发类型错误,已改为str(slot_id)解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:22:40