skip to Main Content

I’m new to python and still I love it but this makes me really frustrated.

I’m trying to load 4 settings in my console app since Write.Input causing errors when converting .exe file, so I was thinking instead let user type and hit enter it would be wise to load some .JSON settings file.
I need to get all values from "amount"; "threads" etc…

My Json settings file settings.json

{ "settings_data":[
    {
        "amount": 1000,
        "threads": 5,
        "type": 1,
        "id": "sK19"
    }
]}

My Code:

with open(os.path.join(sys.path[0], "settings.json"), "r", encoding="utf-8") as f:
    settings = json.loads(f.read())

sendTypeA = json.dumps(settings)
sendTypeB = json.loads(sendTypeA)
sendType = sendTypeB["type"]

ERROR:

    Exception has occurred: KeyError
'type'
File "D:pyprogramsmainmain.py", line 38, in <module>
    sendType = sendTypeB["type"]

2

Answers


  1. Instead of:

    sendType = sendTypeB["type"]
    

    …you need…

    sendType = sendTypeB["settings_data"][0]["type"]
    

    …because the "type" key is in a dictionary that’s in the first element of the list referred to by sendTypeB["settings_data"]

    Login or Signup to reply.
  2. Try the following code:

    with open(os.path.join(sys.path[0], "settings.json"), "r", encoding="utf-8") as f:
        settings = json.loads(f.read())
    
    sendType = settings["settings_data"][0]["type"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search