How to get string of JSON settings in Python

Question:

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"]
Asked By: Jane1990

||

Answers:

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

Answered By: Fred

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"]
Answered By: Kishan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.