JSON file: updated data in the file in wrong format

I am writing a program that will increase the XP of a user that you will type in. As this is still in test phase, the username to add the points to and XP to be updated are fixed.

Source code:

import json

f=open("userData2.json")
userData=json.load(f)



usernameArray=[]

for i in userData["data"]:
    # print(i["username"])
    usernameArray.append(i["username"])

# nameSearch=input("Select name to add XP:")
nameSearch="tinygirl392"

for i in userData["data"]:
    if nameSearch == i["username"]:

        
        index=usernameArray.index(nameSearch)
        oldData=userData["data"][index]
        print(oldData)
        # newXP=input("Enter new XP Value: ")
        newXP=400
        oldData["xp"] += int(newXP)
        newData=json.dumps(oldData)


        print(newData)
        userData["data"].pop(index)
        userData["data"].insert(index,newData)
        print(userData)

        with open("userData2.json", "w") as outfile:
            json.dump(userData, outfile,indent=4)

The JSON file with the names and XP:

{
    "data": [
        {
            "username": "linda4837",
            "realName": "Linda",
            "xp": 0
        },
        {
            "username": "warriorprincess",
            "realName": "Sonya",
            "xp": 0
        },
        {
            "username": "richarab",
            "realName": "Youssef",
            "xp": 0
        },
        {
            "username": "cat9221",
            "realName": "Hina",
            "xp": 0
        },
        {
            "username": "spike_920183",
            "realName": "Larry",
            "xp": 0
        },
        {
            "username": "tinygirl392",
            "realName": "Celia",
            "xp": 0
        },
        {
            "username": "groupsixhunter",
            "realName": "Ophelia",
            "xp": 0
        },
        {
            "username": "fr999281",
            "realName": "Agathe",
            "xp": 0
        },
        {
            "username": "goldendude99",
            "realName": "Mustafa",
            "xp": 0
        },
        {
            "username": "m249_girl",
            "realName": "Claudia",
            "xp": 0
        },
        {
            "username": "rocky888",
            "realName": "Dennis",
            "xp": 0
        },
        {
            "username": "wjh382772",
            "realName": "Wei Jian",
            "xp": 0
        },
        {
            "username": "sakura161",
            "realName": "Maya",
            "xp": 0
        }
    ]
}

When I run it once, the file becomes like this:

{
    "data": [
        {
            "username": "linda4837",
            "realName": "Linda",
            "xp": 0
        },
        {
            "username": "warriorprincess",
            "realName": "Sonya",
            "xp": 0
        },
        {
            "username": "richarab",
            "realName": "Youssef",
            "xp": 0
        },
        {
            "username": "cat9221",
            "realName": "Hina",
            "xp": 0
        },
        {
            "username": "spike_920183",
            "realName": "Larry",
            "xp": 0
        },
        "{\"username\": \"tinygirl392\", \"realName\": \"Celia\", \"xp\": 400}",
        {
            "username": "groupsixhunter",
            "realName": "Ophelia",
            "xp": 0
        },
        {
            "username": "fr999281",
            "realName": "Agathe",
            "xp": 0
        },
        {
            "username": "goldendude99",
            "realName": "Mustafa",
            "xp": 0
        },
        {
            "username": "m249_girl",
            "realName": "Claudia",
            "xp": 0
        },
        {
            "username": "rocky888",
            "realName": "Dennis",
            "xp": 0
        },
        {
            "username": "wjh382772",
            "realName": "Wei Jian",
            "xp": 0
        },
        {
            "username": "sakura161",
            "realName": "Maya",
            "xp": 0
        }
    ]
}

What have I done wrong here?

Why walk all the elements of this, searching for something you’ve already segregated out?
index your usernameArray to find your target, and dont walk the userData array a second time.

Anyway, onto the problem.
newData=json.dumps(oldData)
newData is now a string.

userData["data"].insert(index,newData)
You tell a json object to insert a string. It dutifully does what you asked it to do.

You already know where the data you’re trying to modify is.
Dont… do all of that new variable stuff.

keep index, dump oldData.

userData["data"][index]["xp"] += int(newXp);

Dont do that. userData already contains the modification you want.

1 Like

Summary of above:

import json

f=open("userData2.json")
userData=json.load(f)
usernameArray=[]

for i in userData["data"]:
    usernameArray.append(i["username"])

# nameSearch=input("Select name to add XP:")
nameSearch="tinygirl392"
index=usernameArray.index(nameSearch)
# newXP=input("Enter new XP Value: ")
newXP=400
userData["data"][index]["xp"] += int(newXP)

with open("userData2.json", "w") as outfile:
    json.dump(userData, outfile,indent=4)

(There’s probably a shorter way using comprehensions for the search, but my brain isnt fully engaged at 5:30 in the morning.)

1 Like

Why not just

f=open("userData2.json");
userData=json.load(f);
for(const data of userData)
{
    if(data.username === "tinygirl392")
    {
        data.xp += 400;
        break;
    }
} 
with open("userData2.json", "w") as outfile:
    json.dump(userData, outfile,indent=4)
1 Like
for user in [x for x in userData["data"] if x["username"] == "tinygirl392"]:
    user["xp"] = 400;

(I’m doing some literal insertions there but you get the point)

This is something which I would call “no readable code” but this depends on the readers skills of course.

Yeah, I agree its less readable, but my general experience of python coders is that they would prefer the comprehension rather than the full code. shrug

2 Likes

Yes, but that’s because they all ask ChatGPT how to write the code and that way they do not have so much to copy&paste

SCNR

Here is the Python version:

import json

# Load the JSON data from the file
with open("userData2.json") as f:
    userData = json.load(f)

# Find the user with the specified username and update their XP
for data in userData['data']:
    if data['username'] == 'tinygirl392':
        data['xp'] += 400
        break

# Write the updated data back to the file
with open("userData2.json", "w") as outfile:
    json.dump(userData, outfile, indent=4)
1 Like

Thank you very much! You’re right that I actually didn’t need to take all these extra steps… very appreciated.

Just as an aside, make sure to always close file objects when you’re finished with them, most easily done by using open() as a context manager as you did when opening the same file for writing (also see @Zensei’s snippet).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.