简体   繁体   English

从 Json Dict/Python 中删除密钥

[英]Remove Key From Json Dict/ Python

I Just started writing this script for practice, it will take input and then write it inside Json file.我刚开始写这个脚本来练习,它会接受输入,然后把它写在 Json 文件中。 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: Json 文件如下所示:

{"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:但是当我尝试删除密钥(例如 key3)时,我的 json 文件将是这样的:

{"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?它在 dict 之外取键,但在末尾添加“}”任何想法我能做什么?

EDIT: Also Tried .pop but same result编辑:也试过 .pop 但结果相同

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.这里的错误是运行jjson.seek(0)后跟json.dump(tvsh, jjson)不会破坏现有文件的内容,只会覆盖它。 Since the data structure you are writing to the JSON file after remove Key3 is smaller, the entire file is not overwritten (ie, the "Key3":["Val1","Val2"]} is left over from your first write).由于您在删除Key3后写入 JSON 文件的数据结构较小,因此不会覆盖整个文件(即, "Key3":["Val1","Val2"]}是您第一次写入时遗留的)。

The solution here is to run jjson.truncate() after running json.dump(tvsh, jjson) .这里的解决方案是运行jjson.truncate()运行后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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM