skip to Main Content

I wrote a code to edit json file, but it keep duplicate the content.
How do I delete the duplicated one or prevent it from showing up at all?

Here is the code:

import json

with open('test.json', 'r') as f:
    json_data = json.load(f)
    temp = json_data

a = input('tag: ')
if a in str(temp):
    print('tag claimed')
    b = input('user input: ')
    c = input('responses: ')
    temp["intents"][0]["user_input"].append(b)
    temp["intents"][0]["responses"].append(c)
else:
    d = input('user input: ')
    e = input('responses: ')
    x = {    "tag": (a),
             "user_input": [d],
             "responses": [e],
             "context_set": ""
        }

    temp["intents"].append(x)

    with open('test.json', 'a') as f:
        json.dump(temp, f, indent=4)

When i tried to edit the json, it wrote an entire new one and also keep the old one, like this:

{
    "intents": [
        {
            "tag": "greeting",
            "user_input": ["hi"],
            "responses": ["hello"],
            "context_set": ""
        }
    ]
}{
    "intents": [
        {
            "tag": "greeting",
            "user_input": ["hi"],
            "responses": ["hello"],
            "context_set": ""
        },
        {
            "tag": "goodbye",
            "user_input": ["bye"],
            "responses": ["bye"],
            "context_set": ""
        }
    ]
}

Can anyone help me?
Sorry if my code feel a little clunky, i just started to code a few days ago, and this is also the first time i post on this site

I’m using Python 3.11.3

I haven’t tried any other way beside looking on web for any answer

2

Answers


  1. Replace with open('test.json', 'a') as f:

    With with open('test.json', 'w') as f:

    As 'a' stands for append and 'w' stands for write (truncates the file if it exists).

    Login or Signup to reply.
  2. You’re opening the file with the ‘a’ (append) mode, which appends the new content to the existing content. Instead, you should open the file with the ‘w’ (write) mode, which overwrites the existing content.

    # Use 'w' mode instead of 'a' mode to overwrite the file
    with open('test.json', 'w') as f:
        json.dump(temp, f, indent=4)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search