0

I want to get a random from a json object (random value from different keys) using .split(", ") but then I get an error

My code

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

this is the json file

{

  "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"
  }
}

When I try to generate serials for the g933 key nothing happens and the program does what I want it to do. But when I try to generate serials for anything else I get a Keyerror: "key name"

popsmoke
  • 75
  • 1
  • 1
  • 6
  • Python does not work like this: `if product_finder == "headsets" or "headset":`. Quick fix: `if product_finder in ('headset', 'headsets'):` – slackmart Mar 30 '20 at 02:07

1 Answers1

0

You have an issue with the conditions in your if statements. A non-empty string is always "True" in Python so when you have or "headset" in your conditions they will always return True.

You can use in to test if a value is one of several values

if product_finder in ("headsets", "headset"):
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50