Ad

JSON Formatting Navigation Python

- 1 answer

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.

[0] brings me the first item title.

[-1] brings me the last item title.

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']
Ad

Answer

You can do this by adding an inner loop like this:

r = requests.get("jsonURL", params="jsonparams")
data = r.json()

for items in data['orders']:
    for item in items['line_items']:
       print(item['title'])

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 first n items, then you would write items['line_items'][:n]. If you want to print only the last n items, you would write items['line_items'][-n]. You can even combine the two, for instance items['line_items'][1:-2] will skip the first and last two items in the list.

Ad
source: stackoverflow.com
Ad