【发布时间】:2022-01-12 05:58:54
【问题描述】:
目前,我正在为一个更大的项目使用 Python 中的引导序列。对于序列的这个特定部分,我需要访问一个 .JSON 文件 (specs.json),将其建立为主程序中的字典。然后我需要从 .JSON 文件中获取一个值,并将1 添加到其中,使用它的键来查找该值。完成后,我需要将更改推送到 .JSON 文件。然而,每次我运行下面的代码时,我都会收到错误:
bootNum = spcInfDat['boot_num']
KeyError: 'boot_num'`
这是我目前拥有的代码:
(注意:我使用的是 Python json 库,并导入了 dumps、dump 和 load。)
# Opening of the JSON files
spcInf = open('mki/data/json/specs.json',) # .JSON file that contains the current system's specifications. Not quite needed, but it may make a nice reference?
spcInfDat = load(spcInf)
此代码后面是此代码,我尝试使用它的字典键将值分配给变量(for 语句是调试语句,因此我可以明显看到键):
for i in spcInfDat['spec']:
print(CBL + str(i) + CEN)
# Loacting and increasing the value of bootNum.
bootNum = spcInfDat['boot_num']
print(str(bootNum))
bootNum = bootNum + 1
(另一个注意事项:CBL 和 CEN 只是我用来为发送到终端的文本着色的变量。)
这是specs.json的内部:
{
"spec": [
{
"os":"name",
"os_type":"getwindowsversion",
"lang":"en",
"cpu_amt":"cpu_count",
"storage_amt":"unk",
"boot_num":1
}
]
}
我对 .JSON 文件以及使用 Python json 库比较陌生;我只能通过我找到的一些 GeeksforGeeks 教程来了解他们。很有可能我只是不知道 .JSON 文件如何与库一起工作,但我认为在这里检查仍然值得一试。 GeeksForGeeks 教程没有关于此的文档,而且我对它的工作原理知之甚少,所以我迷路了。我已经尝试在这里搜索,但没有找到任何东西。
问题编号 2
现在,前面的部分起作用了。但是,当我尝试在以下行上运行代码时:
# Changing the values of specDict.
print(CBL + "Changing values of specDict... 50%" + CEN)
specDict ={
"os":name,
"os_type":ost,
"lang":"en",
"cpu_amt":cr,
"storage_amt":"unk",
"boot_num":bootNum
}
# Writing the product of makeSpec to `specs.json`.
print(CBL + "Writing makeSpec() result to `specs.json`... 75%" + CEN)
jsonobj = dumps(specDict, indent = 4)
with open('mki/data/json/specs.json', "w") as outfile:
dump(jsonobj, outfile)
我得到错误:
TypeError: Object of type builtin_function_or_method is not JSON serializable.
是否有可能是我错误地设置了我的字典,还是我错误地使用了dump 函数?
【问题讨论】: