【问题标题】:Key 'boot_num' is not recognized when being interpreted from a .JSON file从 .JSON 文件解释时无法识别键“boot_num”
【发布时间】:2022-01-12 05:58:54
【问题描述】:

目前,我正在为一个更大的项目使用 Python 中的引导序列。对于序列的这个特定部分,我需要访问一个 .JSON 文件 (specs.json),将其建立为主程序中的字典。然后我需要从 .JSON 文件中获取一个值,并将1 添加到其中,使用它的键来查找该值。完成后,我需要将更改推送到 .JSON 文件。然而,每次我运行下面的代码时,我都会收到错误:

bootNum = spcInfDat['boot_num']
KeyError: 'boot_num'`

这是我目前拥有的代码:

(注意:我使用的是 Python json 库,并导入了 dumpsdumpload。)

# 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

(另一个注意事项:CBLCEN 只是我用来为发送到终端的文本着色的变量。)

这是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 函数?

【问题讨论】:

    标签: python json


    【解决方案1】:

    您可以使用以下方式显示数据:

    print(spcInfData)
    

    这表明它是一个字典,其单个条目 'spec' 有一个数组,其第零个元素是一个子字典,其 'boot_num' 条目是一个整数。

    {'spec': [{'os': 'name', 'os_type': 'getwindowsversion', 'lang': 'en', 'cpu_amt': 'cpu_count', 'storage_amt': 'unk', 'boot_num': 1}]}
    

    所以你要找的是

    boot_num = spcInfData['spec'][0]['boot_num']
    

    注意,这样得到的值已经是整数了。 str() 不是必需的。

    防止文件格式错误也是一种很好的做法,以便程序能够优雅地处理它们。

    try:
        boot_num = spcInfData['spec'][0]['boot_num']
    except (KeyError, IndexError):
        print('Database is corrupt')
    

    问题编号 2

    “不可序列化”表示数据结构中的某处不是可接受的类型,无法转换为 JSON 字符串。

    json.dump() 只处理某些类型,例如字符串、字典和整数。这包括嵌套在子字典、子数组等中的所有对象。有关允许的类型的完整列表,请参阅json.JSONEncoder 的文档。

    【讨论】:

    • 我已经尝试过了,现在发现了一个新问题;在帖子中说明,在旧问题下方。
    • 好的,我已经在其他帮助下编辑了我的答案。
    • 欣赏它,伙计。
    猜你喜欢
    • 1970-01-01
    • 2018-06-25
    • 2014-09-15
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多