如何在Python中为嵌套JSON字典的commands数组添加键值对?
问题描述
我正在创建TL1命令的JSON文件,要求将command和CommandType这两个键值对放入data.nodes[].shelves[].scripts[].commands数组内,但当前代码错误地将它们添加到了JSON根层级。尝试过update、append方法,甚至直接写入字典,都出现了类型错误。
目标JSON格式
{ "data": { "nodes": [ { "shelves": [ { "scripts": [ { "commands": [ { "command": "ACT-USER::JAMES:123;", "CommandType": "TL1" } ] } ] } ] } ] } }
当前错误结果
{ "command": "ACT-USER::JAMES:123;", "CommandType": "TL1", "data": { "nodes": [ { "shelves": [ { "scripts": [ { "commands": [] } ] } ] } ] } }
原Python代码
import json # 初始化JSON结构 tl1_json = { "data": { "nodes": [ { "shelves": [ { "scripts": [ { "commands": [] } ] } ] } ] } } # 错误的添加方式 tl1_json["command"] = "ACT-USER::JAMES:123;" tl1_json["CommandType"] = "TL1" # 写入文件 with open("tl1_commands.json", "w") as f: json.dump(tl1_json, f, indent=2)
解决方案
核心问题是没有正确定位到commands数组的层级,直接操作了根字典。需要逐层访问到data.nodes[0].shelves[0].scripts[0].commands(假设只操作第一个node、第一个shelf、第一个script),然后将构造好的命令字典append到该数组中。
修正后的Python代码
import json # 初始化JSON结构 tl1_json = { "data": { "nodes": [ { "shelves": [ { "scripts": [ { "commands": [] } ] } ] } ] } } # 正确定位到commands数组并添加命令 target_commands = tl1_json["data"]["nodes"][0]["shelves"][0]["scripts"][0]["commands"] target_commands.append({ "command": "ACT-USER::JAMES:123;", "CommandType": "TL1" }) # 写入文件 with open("tl1_commands.json", "w") as f: json.dump(tl1_json, f, indent=2)
关键说明
- 层级定位:通过索引
[0]访问数组中的第一个元素,如果需要操作多个node/shelf/script,可通过循环遍历; - 数组操作:
commands是数组类型,必须用append方法添加字典元素,不能直接用update(update是字典方法,用于修改键值对); - 类型检查:确保每一层级的结构存在,避免因索引越界或结构缺失导致的类型错误。如果需要动态创建层级(比如nodes/shelves/scripts为空),需先判断并初始化对应结构。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

