【问题标题】:How to reference a json array element by name using Python?如何使用 Python 按名称引用 json 数组元素?
【发布时间】:2015-12-18 17:16:45
【问题描述】:

在这个json数组中:

json_string=[{"Id": "report","Value": "3001"},{"Id": "user","Value": "user123"}]

如果我传入user

,如何找回user123

当我尝试这样做时:

content = json.loads(json_string) 
content['user']

我收到一条错误消息,提示您必须使用整数来引用元素。

我是 Python 新手。

谢谢!

【问题讨论】:

    标签: python arrays json


    【解决方案1】:

    content 是一个列表,因此您应该首先通过索引获取元素:

    >>> content[1]['Value']
    'user123'
    
    >>> for d in content:
    ...     if 'user' in d.values():
    ...         print d['Value']
    'user123'
    

    假设user 总是映射到Id

    >>> for d in content:
    ...     if d['Id'] == 'user':
    ...         print d['Value']
    

    一个班轮:

     >>> [d['Value'] for d in content if d['Id'] == 'user'][0]
     'user123'
    

    【讨论】:

    • 或更一般地说,[ x for x in content where x['Id'] == "user"][0]["Value"]
    • 谢谢!没办法,给我元素Id是User的那个值?无需参考索引?我知道我可以遍历它,但只是认为它可以在一行中完成。
    • @chepner,是的!而已。谢谢!
    • 无论如何,我认为是。到目前为止,我已经多次编辑了我的评论 :)
    • @chepner 我假设“用户”可能不必总是映射到Id
    【解决方案2】:

    假设您想关注列表中具有给定字段(例如“Id”)和特定值(例如“user”)的元素的第一次出现:

    def look_for(string, field, val):
        return next((el['Value'] for el in string if el[field] == val))
    
    json_string = [{"Id": "report","Value": "3001"}, {"Id": "user","Value": "user123"}]
    found_val = look_for(json_string, 'Id', 'user')
    

    生产

    'user123'
    

    显然,输出字段也可以成为参数而不是硬编码为Value

    【讨论】:

      猜你喜欢
      • 2014-11-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2021-12-30
      • 2011-11-07
      • 2010-11-09
      • 1970-01-01
      相关资源
      最近更新 更多