contactme8359
contactme8359

Reputation: 83

Printing fields from json when applicable

I have a json file that is generated to find the number of items available at any given time (see below). In this scenario, there are 2 items available. There are 9 of item #1 and 5 of item #2. There are 0 of all other items. However, on another day or at another time, there could be 3 or 6 or any number of items available in unknown quantities. How can I write my python to print out how many of each item there are at any given time instead of just when there are a certain number of items available?

{"item": [
    {
        "amount": 9
    },
    {
        "amount": 5
    }
]}

This is my python file. I can successfully print out when there is one item available in a variable quantity. But how can I handle a variable number of items available?

with open(file_name) as f:
    data = json.load(f)

printItem = data["item"][0]["amount"] + ":"
print (printItem)

Upvotes: 0

Views: 218

Answers (1)

Lakshya Raj
Lakshya Raj

Reputation: 1775

The answer is actually quite simple. You just need to loop through each item and print it separately.

with open(file_name) as f:
  data = json.load(f)
  items = data.item
  for item in items:
    print(item.amount)

This will loop every item in the items array from the JSON object and print each individual price.

Here's an explanation of the for loop. We start by defining the for, after which the identifier item declares a variable that will be set each time the loop executes. Then, in is used to signify that we are looping through every item in the object named items. To end the loop definition statement, we use a : and then indent the loop body.

Inside the loop, we can use the item variable as it changes for each different item in the array. The first time around, item will be the zeroth item the array, the second time around it will be the first, and so on. Note that after the loop is over the item variable will still exist. It is actually defined and can be used to reference the last value in the array, even after the loop has completed.

Upvotes: 1

Related Questions