Key 'boot_num' is not recognized when being interpreted from a .JSON file

Viewed 26

Currently, I am working on a Boot Sequence in Python for a larger project. For this specific part of the sequence, I need to access a .JSON file (specs.json), establish it as a dictionary in the main program. I then need to take a value from the .JSON file, and add 1 to it, using it's key to find the value. Once that's done, I need to push the changes to the .JSON file. Yet, every time I run the code below, I get the error:

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

Here's the code I currently have:

(Note: I'm using the Python json library, and have imported dumps, dump, and 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)

This code is later followed by this, where I attempt to assign the value to a variable by using it's dictionary key (The for statement was a debug statement, so I could visibly see the Key):

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

(Another Note: CBL and CEN are just variables I use to colour text I send to the terminal.)

This is the interior of specs.json:

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

I'm relatively new with .JSON files, as well as using the Python json library; I only have experience with them through some GeeksforGeeks tutorials I found. There is a rather good chance that I just don't know how .JSON files work in conjunction with the library, but I figure that it would still be worth a shot to check here. The GeeksForGeeks tutorial had no documentation about this, as well as there being minimal I know about how this works, so I'm lost. I've tried searching here, and have found nothing.

Issue Number 2

Now, the prior part works. But, when I attempt to run the code on the following lines:

# 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)

I get the error: TypeError: Object of type builtin_function_or_method is not JSON serializable.

Is there a chance that I set up my dictionary incorrectly, or am I using the dump function incorrectly?

1 Answers

You can show the data using:

print(spcInfData)

This shows it to be a dictionary, whose single entry 'spec' has an array, whose zero'th element is a sub-dictionary, whose 'boot_num' entry is an integer.

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

So what you are looking for is

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

and note that the value obtained this way is already an integer. str() is not necessary.

It's also good practice to guard against file format errors so the program handles them gracefully.

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

Issue Number 2

"Not serializable" means there is something somewhere in your data structure that is not an accepted type and can't be converted to a JSON string.

json.dump() only processes certain types such as strings, dictionaries, and integers. That includes all of the objects that are nested within sub-dictionaries, sub-arrays, etc. See documentation for json.JSONEncoder for a complete list of allowable types.

Related