I am very new to python so i apologise in advance. I want to grab the image url from the JSON file.
The hierarchy of the JSON file
For example, i can get the the above product ID(16796655) image url by doing:
data = json.loads(script)
img_name = (data['entities']['products']['16796655']['images'])
print(img_name)
and this grabs it just fine.
However I have a list of IDs and would like to just make one request to get each image url that falls under these IDs: 16796655, 17329706, 17741328, 17732192
Do i need to put all my IDs into an array and then do a for and somehow reference the ID array in this section of the data call? ['16796655'] as the data call obviously requires the ID to be referenced inside it in order to know which image url to get.
Thanks for your help
CodePudding user response:
Do i need to put all my IDs into an array and then do a for and somehow reference the ID array in this section of the data call?
Yes that's exactly what you could do.
data = json.loads(script)
products = data["entities"]["products"]
ids = ["16796655", "17329706", "17741328", "17732192"]
to get them all in a list
all_images = [products[i]["images"] for i in ids if i in products]
although I suggest putting them into a dict so you can assign the id to their respective images
all_images = {i: products[i]["images"] for i in ids if i in products}
or if you only need to print them
for i in ids:
if i in products:
print(products[i]['images'])
Bonus, using operator.itemgetter
(assuming all ids exist in products or you get an error):
get_ids = operator.itemgetter(*ids)
get_image = operator.itemgetter("images")
all_images = dict(zip(ids, map(get_image, get_ids(products))))
#result is the same as my dict approach
CodePudding user response:
ids = ["16796655", "17329706", "17741328", "17732192", ...]
for i in ids:
if i in data['entities']['products']:
img_name = (data['entities']['products'][i]['images'])
print(img_name)
This should work.