Anton Erjomin
Anton Erjomin

Reputation: 183

Rewrite object into json

I have a json with users data. I need to make 2 methods: 1) delete user by ID 2) change some information into user

This is example of my json:

{
    "users": [
        {
            "last result": 15,
            "login": "admin",
            "id": 1,
            "password": "1"
        },
        {
            "last result": 2,
            "login": "user",
            "id": 2,
            "password": "1"
        }
    ]
}

Method for remove looks like this:

def load_data_from_json(test_file_name):
    with open(test_file_name, encoding="utf-8") as data_file:
        return json.load(data_file)

def remove_user_by_id(id):
    jobject = load_data_from_json("auth.json")["users"]
    for user in jobject:
        if user["id"] == id:
            jobject.pop(user)
        break

But i don't know how to add new data into json, i mean to rewrite.

Method for rewriting some data should look like this:

def set_last_result(login, new_result):
    for user in load_data_from_json("auth.json")["users"]:
        if user["login"] == login:
            user["last result"] = new_result

User story:

User make test and take new test result, for example it is Admin user and his new test result should be 55. How can I add this result into my json?

Upvotes: 1

Views: 180

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123930

You can simply write the data right back again:

def load_data_from_json(test_file_name):
    with open(test_file_name, encoding="utf-8") as data_file:
        return json.load(data_file)

def save_data_to_json(data, test_file_name):
    with open(test_file_name, 'w', encoding="utf-8") as data_file:
        return json.dump(data, data_file)

def remove_user_by_id(id):
    jobject = load_data_from_json("auth.json")
    jobject['users'] = [
        user for user in jobject["users"]
        if user["id"] != id]
    save_data_to_json(jobject, 'auth.json')

def set_last_result(login, new_result):
    jobject = load_data_from_json("auth.json")
    for user in jobject["users"]:
        if user["login"] == login:
            user["last result"] = new_result
    save_data_to_json(jobject, 'auth.json')

In the remove_user_by_id() and set_last_result() functions, I've stored the top level object returned from the load_data_from_json function; you can then pass that object back to json.dump() (via the new save_data_to_json() function, to mirror your setup).

Users are removed by filtering; a list comprehension includes all users that are not the user you wanted removed.

Upvotes: 2

Related Questions