Skip to content Skip to sidebar Skip to footer

Python Json. Getting Only The Last Element In The Json Array

I just started trying out python, and right now i am in a little bit of a dilemma. I am trying to print from a json documents, and i am only getting the last element in the array.

Solution 1:

You are replacing the value every time through that loop. You should be adding to the value, instead.

So first create the value as an empty list (before the loop), then on each iteration of the loop, append to that list:

value = []
rec = recipes['Recipes'][0]['Ingredients']
for records in rec:
    value.append({'Ingredient ID': records['IngredientID']})

However, having a list of dictionaries, where each dictionary has one single value with the same known key, seems a bit pointless. Depending on your requirements, you probably may want to do either this:

    value.append(rec)

or

    value.append(records['IngredientID'])

Solution 2:

What you're doing right now is that you're redefining value again every loop. You will need to define value before the loop and assign it to an empty list that you can add to.

value = {'Ingredient ID':[]}
for records in rec:
    value['Ingredient ID'].append(records['IngredientID'])

You can also define value as a list like this:

value = []
for records in rec:
    value.append(records['IngredientID'])

Solution 3:

You are re-assigning variable value everytime. Hence you are getting the last element. Instead you should try

# Your code
value = []
for records in rec:
    value.append(records['IngredientID']);

# print value     # this will have all required IngredientID

Solution 4:

One issue with your current implementation is that the value of value will be over-written each time you find a new ingredient ID. If you need to get a list of values, then you have to make sure that you keep all of the old values even when adding a new one.

If you make values a list and then use append, you'll get all of the values you are looking for:

values = []
forrecordsin rec:
    ingredient_id = records.get('IngredientID', None)
    if ingredient_id:
        values.append(ingredient_id)

It is a good idea to use the dict.get() method to retrieve a value and then check if it exists; otherwise you may end up with an exception.

Solution 5:

If you just wanted the ids, you could use a list comprehension, something like this:

ids = [records['IngredientID'] for records in recipes['Recipes'][0]['Ingredients']]

Post a Comment for "Python Json. Getting Only The Last Element In The Json Array"