1

I Just started writing this script for practice, it will take input and then write it inside Json file. Code looks like this:

import json


command = int(input("Do You Want To Add, Or Remove From List? 1/2 "))
if command == 1:
    add_key = input("Type In key Name: ")
    add_val1 = input("Type In Value N1: ")
    add_val2 = input("Type In Value N2: ")

    with open('jjj.json', 'r+') as jjson:
        tvsh = json.load(jjson)
        new_tvsh = {add_key: [add_val1, add_val2]}
        tvsh.update(new_tvsh)
        jjson.seek(0)
        json.dump(tvsh, jjson)
elif command == 2:
    with open('jjj.json', 'r+') as jjson:
        tvsh = json.load(jjson)
        chooseremove = input("Choose Key To Remove: ")
        try:
            del tvsh[chooseremove]
        except KeyError as ex:
            print(f"No such key: {chooseremove} ")
        jjson.seek(0)
        json.dump(tvsh, jjson)

Json File Looks Like This:

{"Key1":["Val1","Val2"],"Key2":["Val1","Val2"],"Key3":["Val1","Val2"]}

But when i try to remove key(For example key3) my json file will be like this:

{"Key1":["Val1","Val2"],"Key2":["Val1","Val2"]} "Key3":["Val1","Val2"]}

it's taking key outside dict but adding "}" at the end Any Ideas what can i do?

EDIT: Also Tried .pop but same result

1
  • 2
    Try creating a minimal reproducible example, which does not take user input but only does what is needed to reproduce the problem when it is run. Commented Oct 20, 2020 at 1:30

1 Answer 1

2

The error here is that running jjson.seek(0) followed by json.dump(tvsh, jjson) does not destroy the contents of the existing file, it only overwrites it. Since the data structure you are writing to the JSON file after remove Key3 is smaller, the entire file is not overwritten (i.e., the "Key3":["Val1","Val2"]} is left over from your first write).

The solution here is to run jjson.truncate() after running json.dump(tvsh, jjson).

The following program shows the difference, without depending on user input:

#!/usr/bin/env python3

import json

# Test data
initial_data = {
    "Key1":["Val1", "Val2"],
    "Key2":["Val1", "Val2"],
    "Key3":["Val1", "Val2"],
}
final_data = {
    "Key1":["Val1", "Val2"],
    "Key2":["Val1", "Val2"],
}

with open('testA.json', 'w') as f:
    json.dump(initial_data, f)
    f.seek(0)
    json.dump(final_data, f)

with open('testB.json', 'w') as f:
    json.dump(initial_data, f)
    f.seek(0)
    json.dump(final_data, f)
    f.truncate()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.