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
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).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.