[英]How to group all objects in an array that correspond to the same JSON name/value
[英]How to format the same name value into an array
我有這個 JSON 數據
{
"Label": "Color Roles",
"Pool": "Colors",
"Hidden": false,
"Limit": -3,
"Message": "Pick a colored role to start with <3",
"Roles": [
{
"Name": "Apple★",
"Print": "Apple",
"Aliases": ".iam Apple",
"Aliases1": [
".iam Apple",
"+Apple"
]
},
{
"Name": "Clementine★",
"Print": "Clementine",
"Aliases": [
".iam Clementine",
"+Clementine"
]
},
{
"Name": "Sunflower★",
"Print": "Sunflower",
"Aliases": [
".iam Sunflower",
"+Sunflower"
]
},
{
"Name": "Mint★",
"Print": "Mint",
"Aliases": [
".iam Mint",
"+Mint"
]
},
{
"Name": "Ocean★",
"Print": "Ocean",
"Aliases": [
".iam Ocean",
"+Ocean"
]
},
{
"Name": "Grape★",
"Print": "Grape",
"Aliases": [
".iam Grape",
"+Grape"
]
},
{
"Name": "Candy Floss★",
"Print": "Candy Floss",
"Aliases": [
".iam Candy Floss",
"+Candy Floss"
]
}
]
}
]
我想將"Roles"
中的所有"Name
”格式化為一個數組然后打印。我只能使用代碼打印第一個“名稱”
print(data['roles'][0]['name'])
我怎樣才能讓它格式化以便打印
["Apple★","Clementine★","Sunflower★","Mint★","Ocean★","Grape★","Candy Floss★"]
然后將該數據保存在數組中以用於另一個功能,該功能將充當
values = ["Apple★","Clementine★","Sunflower★","Mint★","Ocean★","Grape★","Candy Floss★"]
info = requests.get(https://api.url.com/{Values?}
只是對循環中的每個值進行請求
您可以對Roles
dicts 使用列表理解來獲取Name
屬性:
values = [role['Name'] for role in data['Roles']]
輸出(用於您的樣本數據):
["Apple★", "Clementine★", "Sunflower★", "Mint★", "Ocean★", "Grape★", "Candy Floss★"]
jsonpath
包專用於 python 處理 json 數據。
您只需要學習一些簡單的語法即可進行操作。
from jsonpath import jsonpath
data = {
"Label": "Color Roles",
"Pool": "Colors",
"Hidden": "false",
"Limit": -3,
"Message": "Pick a colored role to start with <3",
"Roles": [
{
"Name": "Apple★",
"Print": "Apple",
"Aliases": ".iam Apple",
"Aliases1": [
".iam Apple",
"+Apple"
]
},
{
"Name": "Clementine★",
"Print": "Clementine",
"Aliases": [
".iam Clementine",
"+Clementine"
]
},
{
"Name": "Sunflower★",
"Print": "Sunflower",
"Aliases": [
".iam Sunflower",
"+Sunflower"
]
},
{
"Name": "Mint★",
"Print": "Mint",
"Aliases": [
".iam Mint",
"+Mint"
]
},
{
"Name": "Ocean★",
"Print": "Ocean",
"Aliases": [
".iam Ocean",
"+Ocean"
]
},
{
"Name": "Grape★",
"Print": "Grape",
"Aliases": [
".iam Grape",
"+Grape"
]
},
{
"Name": "Candy Floss★",
"Print": "Candy Floss",
"Aliases": [
".iam Candy Floss",
"+Candy Floss"
]
}
]
}
print(jsonpath(data, "$..Name"))
出去
['Apple★', 'Clementine★', 'Sunflower★', 'Mint★', 'Ocean★', 'Grape★', 'Candy Floss★']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.