Python 3 如何在 JSON 中为嵌套字典添加 key:value

python 3 how to add key:value to nested dict in json

提问人:James 提问时间:3/27/2023 更新时间:3/27/2023 访问量:36

问:

我正在尝试为 TL1 命令创建一个 json 文件。我得到的格式是:

{
"data": {
    "nodes": [
        {
            "deviceType": "6500",
            "nodeName": "hostNameHere",
            "Shelf Type": "Transponder",
            "shelves": [
                {
                    "primary": "DISABLE",
                    "scripts": [
                        {
                            "commands": [{}]
                        }
                    ]
                }
            ]
        }
    ]
}
}

我最终会得到

{
"data": {
    "nodes": [
        {
            "deviceType": "6500",
            "nodeName": "hostNameHere",
            "Shelf Type": "Transponder",
            "shelves": [
                {
                    "primary": "DISABLE",
                    "scripts": [
                        {
                            "commands": [
                                {}
                            ]
                        }
                    ]
                }
            ]
        }
    ]
},
"command": "SET-SID:GenTid1::CTAG::\"hostNameHere\";",
"CommandType": "tl1"
}

我需要“commands:”[] 下的命令和 commandType 尝试过更新,append 甚至尝试将命令和命令类型直接放入字典中

 {
                             "commands": [
{
   "command": "SET-SID:GenTid1::CTAG::\"hostNameHere\";",
"CommandType": "tl1"}    ]
                                 
                             }

但出现了类型集错误

关于如何在正确的位置获得命令的任何建议?

我的代码:

root = tk.Tk()
root.attributes("-topmost", True)
root.withdraw()
file = tkinter.filedialog.askopenfilename()

Dir_Path = (os.path.dirname(file) )
fName = os.path.basename(Dir_Path)
def TL1_script (TL1_Command):
    fReport = open ("%s\%s_TL1.txt" %(Dir_Path, fName), "a" )
    fReport.write("\"command\": \"%s\",\r" %(TL1_Command) )
    fReport.close()

def Type_script (CommandType):
    fReport = open ("%s\%s_TL1.txt" %(Dir_Path, fName), "a" )
    fReport.write("\"commandType\": \"%s\"\r" %(CommandType) )
    fReport.close()

TL1 = ("SET-SID:GenTid1::CTAG::\"%s\";" %(TID) )
CommandType = ("tl1")
TL1_Command = TL1_script(TL1)
Type = Type_script (CommandType)



i= {"data": {
        "nodes": [
            {
                "deviceType": "6500",
                "nodeName": "%s" %(TID),
                "Shelf Type": "%s" %(Shelf_Type),
                "shelves": [
                    {"primary": "%s" %(Primary),
                     "scripts": [
                         {
                             "commands": [{}]
                                 
                             }
                         ]
                     }
                ]
            }
        ]
    }
}

key = {"command"}
value = ["%s" %(TL1)]
key1 = ["CommandType"]
value1 = ["%s" %(CommandType)]

i.update(dict(zip(key, value)))
i.update(dict(zip(key1, value1)))

with open("%s\%s_TL1.json" %(Dir_Path, fName), "a") as outfile:
    json.dump(i, outfile, indent=4)

print(json.dumps(i, indent=8))

我有一个文本文件,其中包含 TL1 命令的所有键值对,我需要将这些命令添加到该命令部分下的 json 文件中

json python-3.x 字典 嵌套

评论


答:

1赞 ProfDFrancis 3/27/2023 #1

您需要将更新定向到字典中的正确位置

key = "command"
value = ["%s" %(TL1)]
key1 = "CommandType"
value1 = ["%s" %(CommandType)]

i["data"]["nodes"][0]["shelves"][0]["scripts"][0]["commands"] = {key:value, key1:value1}

with open("%s\%s_TL1.json" %(Dir_Path, fName), "a") as outfile:
    json.dump(i, outfile, indent=4)
print(json.dumps(i, indent=8))

评论

0赞 James 3/27/2023
我之前确实尝试过帽子,但没有=.。使用点符号..试过了,我得到 TypeError: unhashable type: 'set'
0赞 ProfDFrancis 3/27/2023
对不起,我不明白。当您尝试我提供的代码时发生了什么?
0赞 James 3/27/2023
TypeError:不可哈希 类型:“set”
0赞 ProfDFrancis 3/27/2023
啊,我明白了 - 之后还有一层.我已经更新了 - 再试一次。nodes
1赞 James 3/27/2023
完美,奏效了......非常感谢。。仍在学习 python,我今天搜索了 5 个小时,并尝试了很多不同的东西。