I am trying to retrieve the titles of multiple items that have been under a single order.
There can be multiple subsections under the ‘line_items’ where the information of each item is displayed, title being one of the parameters for every item.
How do I interact with the subsections in between? Is there a way to return all associated order titles whether there’s 1 or more?
r = requests.get("jsonURL", params="jsonparams")
data = r.json()
for item in data['orders']:
purchased = item['line_items'][0]['title']
purchased1 = item['line_items'][-1]['title']
3
Answers
You can do this by adding an inner loop like this:
This will print out the titles of the items in each of the orders.
If you only want to print out a subset of the items you can use a slice on the
items['line_items']
. If you want to print only the firstn
items, then you would writeitems['line_items'][:n]
. If you want to print only the lastn
items, you would writeitems['line_items'][-n]
. You can even combine the two, for instanceitems['line_items'][1:-2]
will skip the first and last two items in the list.Hope this helps for you.
If you want to get the first index:
If you want to get the first index:
The JSON from your code will look somewhat like this:
So, in order to get titles for all items, loop through each item in the
line_items
list, look for the ‘title’ key and append its values to an empty list calledpurchased
:If you also want the quantity of each item purchased, you can use
Counter
: