3

I have the following code where I want to be able to manually input the JSON keys to return the value

import json

with open('profile') as edstats:
    data = json.load(edstats)

def stats():
    r = data[raw_input('JSON Keys:')]
    return r

I run the following and get this error.

>>> execfile('edjson.py')
>>> credits()
JSON Keys:['commander']['name']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "edjson.py", line 7, in credits
    r = data[raw_input('JSON Keys:')]
KeyError: "['commander']['name']"
>>>

Below is a sample of the JSON file:

{
"commander": {
    "id": 1111111,
    "name": "xxxxxxxx",
    "credits": 12345678,
    "debt": 0,
    "currentShipId": 2,
    "alive": true,
    "docked": false,
    "rank": {
        "combat": 3,
        "trade": 4,
        "explore": 5,
        "crime": 0,
        "service": 0,
        "empire": 0,
        "federation": 0
    }
},
"lastSystem": {
    "id": "12342356464335",
    "name": "xxxx xxx xxxx"
}
}

1 Answer 1

2

You can also take the list of keys from the user as comma separated values:

import json

with open('profile.json') as edstats:
    data = json.load(edstats)
inp = raw_input('JSON Keys:').split(',')
r = data
for item in inp:
    r = r[item]
print r

>>> python script.py
JSON Keys:commander,name
xxxxxxxx

>>> python script.py
JSON Keys:commander,rank,explore
5
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this did the trick... now for me to understand what it does.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.