Home > database >  How to get string of JSON settings in Python
How to get string of JSON settings in Python

Time:12-24

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:\pyprograms\main\main.py", line 38, in <module>
    sendType = sendTypeB["type"]

CodePudding user response:

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

CodePudding user response:

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

  • Related