How to parse json to get all values of a specific key within an array?

前端 未结 3 1905
自闭症患者
自闭症患者 2021-01-18 02:39

I\'m having trouble trying to get a list of values from a specific key inside an json array using python. Using the JSON example below, I am trying to create a list which co

3条回答
  •  日久生厌
    2021-01-18 02:53

    You cannot do contents[:]["name"] since contents is a list is a dictionary with integer indexes, and you cannot access an element from it using a string name.

    To fix that, you would want to iterate over the list and get the value for key name for each item

    import json
    contents = []
    
    try:
        with open("./simple.json", 'r') as f:
            contents = json.load(f)
    except Exception as e:
        print(e)
    
    
    li = [item.get('name') for item in contents]
    print(li)
    

    The output will be

    ['Bulbasaur', 'Ivysaur']
    

提交回复
热议问题