如何解析json以获取数组中特定键的所有值? [英] How to parse json to get all values of a specific key within an array?
问题描述
我在尝试使用python从json数组中的特定键中获取值列表时遇到麻烦.使用下面的JSON示例,我试图创建一个仅包含name
键值的列表.
原始JSON:
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 consists only the values of the name
key.
Original JSON:
[
{
"id": 1,
"name": "Bulbasaur",
"type": [
"grass",
"poison"
]
},
{
"id": 2,
"name": "Ivysaur",
"type": [
"grass",
"poison"
]
}
]
预期:
["Bulbasaur", "Ivysaur"]
下面是我的方法的代码:
Below is the code of my approach:
import json
try:
with open("./simple.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
print(contents[:]["name"])
我正在尝试一种不需要循环每个索引并附加它们的方法,就像上面的代码一样.使用python的json库可以实现这种方法吗?
I'm trying to go to an approach where i don't need to loop every single index and append them, something like the code above. Is this approach possible using python' json library?
推荐答案
您不能执行contents[:]["name"]
,因为contents
是一个包含整数索引的列表,并且您不能使用字符串
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
.
要解决此问题,您需要遍历列表并为每个item
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)
输出将是
['Bulbasaur', 'Ivysaur']
这篇关于如何解析json以获取数组中特定键的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!