带有json文件的.split()返回keyerror



我想使用.split(", ")从json对象(来自不同键的随机值(中获得一个随机值,但随后我得到了一个错误

我的代码

import urllib.request
from urllib.request import Request
import json
import random
import sys
import time
import string
url = Request("url", headers={'User-Agent': 'Mozilla/5.0'})
data = urllib.request.urlopen(url).read().decode()
serial = json.loads(data)
chars = string.digits + string.ascii_uppercase
product_finder = input("Type of product to generate? (Headset, Keyboard, etc.): ").lower()
base = input("What product would you want to generate? (G933, GPRO, etc.): ").lower()
amount = int(input("How many serials do you want to generate?: "))
def failed():
print("Could not find your product... termianting program")
time.sleep(3)
sys.exit()
#HEADSETS
if product_finder == "headsets" or "headset":
product = "headset"
if base in serial[product_finder]:
print("Your product has been found! Going to be generating serials for " + base)
base = base
else:
failed()
# KEYBOARDS
elif product_finder == "keyboard" or "keyboards":
product = "keyboard"
if base in serial[product_finder]:
print("Your product has been found! Going to be generating serials for " + base)
base = base
else:
failed()
elif product_finder == "mouse" or "mice":
product = "mouse"
if base in serial[product_finder]:
print("Your product has been found! Going to be generating serials for " + base)
base = base
else:
failed()
def generate():
return "".join([random.choice((serial[product][base]).split(", "))]) + "".join([random.choice(chars) for x in range(2)]) + "8"
for archie in range(amount):
print(generate())

这是json文件

{
"headset": {
"g933": "1904MH01J, 1904MH01M, 1904MH01L, 1904MH01N"
},
"keyboard": {
"gpro": "yes, no"
},
"mouse": {
"g502": "1917LZ56E, 1917LZ54Z, 1917LZ54Z, 1917LZ54Y, 1917LZ53X",
"lightspeed": "1917LZ56E, 1917LZ53X",
"g903": "1917LZ56E"
},
"racing": {
},
"misc": {
"brio4k": "1917LZ55D, 1917LZ54D",
"brio": "1917LZ55D, 1917LZ54D",
"c922": "1917LZ56A",
"c920": "1917LZ54Z, 1917LZ53X, 1917LZ53X"
}
}

当我尝试为g933键生成串行时,什么都没有发生,程序也按照我的意愿执行。但当我尝试生成其他任何东西的串行时,我会得到Keyerror: "key name"

您的if语句中的条件有问题。非空字符串在Python中始终为"True",因此当条件中有or "headset"时,它们将始终返回True

您可以使用in来测试一个值是否是的几个值之一

if product_finder in ("headsets", "headset"):

最新更新