2

I need to be able to get the index position of a certain item within a JSON file using Python so that I am able to append something to another item within that same position.

JSON below:

{
    "members": [{
            "username": "John Doe#0001",
            "possesions": []
        },
        {
            "username": "Samantha Green#0001",
            "possesions": []
        }
    ]
}

I need to find what position in members John Doe#0001 is in for example. So I can then append something to the possesions list like so:

data = json.load(jsonFile)
temp = data['members'][Index position]['possesions']
temp.append("something")

Ive tried googling to no success.

3 Answers 3

2

You can loop through all the members until you find the one you want:

data = json.load(jsonFile)
for member in data['members']:
    if member['username'] == 'John Doe#0001':
        member['posessions'].append(something)
Sign up to request clarification or add additional context in comments.

1 Comment

This solution skips the index number altogether, which is usually simpler; however, if the index number is needed for some purpose, the enumerate built-in function can provide it: for i, member in enumerate(data['members']): ...
0

The JSON is a dictionary in Python. It is not indexed but can be looped through using keys. If you want to replace the value of the particular key, you can replace directly using

data["key"]=new_value

Comments

0
import json
    
json_file={
    "members": [{
            "username": "John Doe#0001",
            "possesions": []
        },
        {
            "username": "Samantha Green#0001",
            "possesions": []
        }
    ]
}

dicti = json.loads(json_file)

for i in range(len(dicti)):
    if dict['members'][i]['username'] == "John Doe#0001":
        print(i)

But before that, you must check if your data is in JSON format. If it is in the dictionary then it will show an error in this

dicti = json.loads(json_file) line.

1 Comment

You want range(len(dict['members'])), not range(len(dict)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.