【问题标题】:JSON KeyError parsing inputJSON KeyError 解析输入
【发布时间】:2015-04-19 20:06:13
【问题描述】:

我有以下代码,我希望能够手动输入 JSON 键以返回值

import json

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

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

我运行以下命令并收到此错误。

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

以下是 JSON 文件的示例:

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

【问题讨论】:

    标签: python json keyerror


    【解决方案1】:

    您还可以将用户的键列表作为逗号分隔值:

    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
    

    【讨论】:

    • 非常感谢,这成功了...现在让我了解它的作用.. :)
    猜你喜欢
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多