[Python] I do not understand how json.dump() in Python works in my specific case

Discussão em 'Python' iniciado por Stack, Maio 17, 2025.

  1. Stack

    Stack Membro Participativo

    I understood that json.dump() means that you will dump all the variable in json format into your json file.

    I ran it perfectly in the first file:

    import json

    def write_json(new_data, file_name="data/emp_details.json"):
    with open(file_name, 'r+') as f:
    file_data = json.load(f)
    file_data["emp_details"].append(new_data)
    print(file_data)
    f.seek(0)
    json.dump(file_data, f, indent=2)

    new_data = {"emp_name": "Nikhil",
    "email": "nikhil@geekforgeeks.org",
    "job_profile": "Full Time"}

    write_json(new_data)


    Here is the file before running:

    {
    "emp_details": [
    {
    "emp_name": "Shubham",
    "email": "ksingh.shubh@gmail.com",
    "job_profile": "intern"
    },
    {
    "emp_name": "Gaurav",
    "email": "gaurav.singh@gmail.com",
    "job_profile": "developer"
    }
    }


    Here is it after running:

    {
    "emp_details": [
    {
    "emp_name": "Shubham",
    "email": "ksingh.shubh@gmail.com",
    "job_profile": "intern"
    },
    {
    "emp_name": "Gaurav",
    "email": "gaurav.singh@gmail.com",
    "job_profile": "developer"
    },
    {
    "emp_name": "Nikhil",
    "email": "nikhil@geekforgeeks.org",
    "job_profile": "Full Time"
    }
    }


    It worked perfectly as my intention.

    But when I moved to the second file, I applied the same steps, but it did not work and confused me a lot.

    with open("data/encouraging_message.json", "r+") as f:
    f.seek(0)
    data = f.read()
    # print(data)
    if data == "":
    file_structure = {"encouragements": [encouraging_message]}
    # print(file_structure)
    json.dump(file_structure, f, indent=2)
    else:
    f.seek(0)
    data = json.load(f)
    # print(data)
    print(data["encouragements"])
    data["encouragements"].append(encouraging_message)
    print(data["encouragements"])
    print(data)
    f.seek(0)
    json.dump(data, f, indent=2)


    Here is the encouraging_message.json file:

    {
    "encouragements": [
    "You will be fine!",
    "You will be fine!"
    ]
    }


    I want the result to be like this:

    {
    "encouragements": [
    "You will be fine!",
    "You will be fine!",
    "You will be fine!"
    ]
    }


    But instead, it worked like this:

    {
    "encouragements": [
    "You will be fine!",
    "You will be fine!"
    ]
    }"You will be fine!"
    ]
    }


    I tried to look around and read some documentations, but I cannot find the results.

    Can anyone explain for me that why it worked like this, and how to fix it ?

    Thanks in advance.

    Continue reading...

Compartilhe esta Página