Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting size of JSON array and read it's elements Python

I have an json array that looks like this:

{
        "inventory": [
            {
                "Name": "katt"
            },
            {
                "Name": "dog"
            }
        ]
}

And now I want to access this array in a program that I'm creating and remove a element, for example "Name": "dog". I'm not super familiar with how to work with json in python, but so far I have tried something like this:

import json

jsonfile = open("viktor.json", "r")
jsonObj = json.load(jsonfile)

jsonfile.close()

counter = 0
for item in range(len(jsonObj["inventory"])):
    print(jsonObj["inventory"][counter])
    print(type(jsonObj["inventory"][counter]))
    if jsonObj["inventory"][counter] == argOne:
        print("hej")
counter += 1

So first I read from the json and stores the data in a variable. Then I want to loop through the whole variable and see if I can find any match, and if so, I want to remove it. I think I can use a pop() method here or something? But I can't seem to get my if-statement to work properly since the jsonObj["inventory"][counter] is a dict and argOne is a string.

What can I do instead of this? Or what I'm missing?

like image 703
anderssinho Avatar asked May 10 '26 07:05

anderssinho


1 Answers

Making the change suggested by @arvindpdmn (to be more pythonic).

for index, item in enumerate(jsonObj["inventory"]):
    print(item)
    print(type(item))  # Here we have item is a dict object
    if item['Name'] == argOne:  # So we can access their elements using item['key'] syntax
        print(index, "Match found")

The for loop is responsible to go through the array, which contains dict objects, and for each dict it will create a item variable that we use to try to get a match.

edit In order to remove the element if it is in the list, I suggest you to use this:

new_list = []
for item in jsonObj["inventory"]:
    if item['Name'] is not argOne:  # add the item if it does not match
        new_list.append(item)

This way you will end with the list you want (new_list).

# Or shorter.. and more pythonic with comprehensions lists.
new_list = [item for item in jsonObj['inventory'] if item['Name'] is not argOne]
like image 87
slackmart Avatar answered May 12 '26 22:05

slackmart