如何更新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)
实现步骤
- 解析JSON字符串为Python字典:用
json.loads把存储的JSON字符串转成可直接操作的字典结构。 - 拼接目标Slot键名:将
slot_id转为字符串后拼接成slotX格式的键名。 - 更新指定Slot的键值:通过字典索引直接修改对应Slot内的各个字段值。
- 转回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
相关产品推荐
相关产品推荐

