Python在JSON数组中获取值

时间:2019-06-18 00:58:48

标签: arrays json python-3.x

在Python 3-x中,请考虑您具有JSON语法的数组:

members = '''[
    {
        "name" : "Amber",
        "age"  : 5 
    },
    {
        "name" : "Becky",
        "age"  : 4 
    }
]'''

agename的情况下,如何获取Amber的值? (答案应该是5。)

1 个答案:

答案 0 :(得分:1)

变量成员看起来像一个字符串,因此首先将字符串更改为json对象并搜索所需内容。

members = '''[
        {
            "name" : "Amber",
            "age"  : 5 
        },
        {
            "name" : "Becky",
            "age"  : 4 
        }
    ]'''
    import json
    obj = json.loads(members) #Changing string to json
    for some_variable in obj:
        if some_variable['name'] == 'Amber':
            print (some_variable['age']) # will print 5