I have this JSON 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"
]
}
]
}
]
I want to format all "Name
within "Roles"
into an Array then print. I can only print the first "Name" using the code
print(data['roles'][0]['name'])
How can I get it to format so it'd print
["Apple★","Clementine★","Sunflower★","Mint★","Ocean★","Grape★","Candy Floss★"]
Then save that data in the array to use for another function which would act as
values = ["Apple★","Clementine★","Sunflower★","Mint★","Ocean★","Grape★","Candy Floss★"]
info = requests.get(https://api.url.com/{Values?}
just to do a request with each value in a loop
CodePudding user response:
You can use a list comprehension over the Roles
dicts to get the Name
properties:
values = [role['Name'] for role in data['Roles']]
Output (for your sample data):
["Apple★", "Clementine★", "Sunflower★", "Mint★", "Ocean★", "Grape★", "Candy Floss★"]
CodePudding user response:
The jsonpath
package is dedicated to python processing json data.
You just need to learn some simple syntax to operate.
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"))
out
['Apple★', 'Clementine★', 'Sunflower★', 'Mint★', 'Ocean★', 'Grape★', 'Candy Floss★']