简体   繁体   English

如何摆脱 JSON 中多余的花括号?

[英]How to get rid of extra curly braces in JSON?

I'm basically creating a contact book, and I want to do it storing data on JSON to practice it.我基本上是在创建一个通讯录,我想在 JSON 上存储数据来练习它。 I have sort a code that allows it from a dictionary, but the problem is that when I rerun the script, another dictionary is appended into the existing one, creating a couple of extra braces which throws the error "End of file expected."我已经对允许从字典中使用它的代码进行了排序,但问题是当我重新运行脚本时,另一个字典被附加到现有的字典中,创建了几个额外的大括号,从而引发错误“预期文件结束”。

This is the code:这是代码:

import json


new_contacts = {}


def contacts():
    while True:
        name = input("Contact's name: ")
        email = input("Email: ")
        number = input("Phone number: ")
        new_contacts[name] = {"email": email, "number": number}
        
        """cursor.execute(
            'INSERT INTO contacts VALUES (?, ?, ?)',
            (name, email, number)
            )"""
        restart_or_not = input("Continue? y/n ").lower()

        if restart_or_not == "y":
            print(new_contacts)
            continue
        else:
            with open('contact_book.json', 'a') as file:
                json.dump(new_contacts, file, indent=4)
            break


contacts()

And this is a sample of a JSON that comes out from it:这是从中得出的 JSON 的样本:

{
    "d": {
        "email": "e",
        "number": "3"
    },
    "h": {
        "email": "y",
        "number": "6"
    },
    "f": {
        "email": "r",
        "number": "3"
    },
    "n": {
        "email": "j",
        "number": "9"
    }
}{
    "g": {
        "email": "j",
        "number": "0"
    }
}

The first four entries don't create any problem because they are appended in the same run, but if I quit the program and rerun it (example "g") then the new dictionary creates the conflict.前四个条目不会产生任何问题,因为它们是在同一次运行中附加的,但是如果我退出程序并重新运行它(例如“g”),那么新字典就会产生冲突。 Any tips?有小费吗?

One way of doing it, is before adding to the file, you delete the last closing bracket } and before dumping, you cast your dict into a string and remove the first bracket using this your_string[1:] .一种方法是,在添加到文件之前,删除最后一个右括号}并在转储之前,将 dict 转换为字符串并使用your_string[1:]删除第一个括号。

The other way which I coded for you, is you load the json into a variable, add the new inputs and then re dump it into the file我为您编写的另一种方法是将 json 加载到变量中,添加新输入,然后将其重新转储到文件中

import json

from os import path # it helps to check if file exists


new_contacts = {}

def contacts():
    while True:
        name = input("Contact's name: ")
        email = input("Email: ")
        number = input("Phone number: ")
        new_contacts[name] = {"email": email, "number": number}
        
        """cursor.execute(
            'INSERT INTO contacts VALUES (?, ?, ?)',
            (name, email, number)
            )"""
        restart_or_not = input("Continue? y/n ").lower()

        if restart_or_not == "y":
            print(new_contacts)
            continue
        else:
            # if the file doesn't exist, write an empty json object into it
            # which will make it easier later to load data from
            if not path.exists('contact_book.json'):
                with open('contact_book.json', 'w+') as file:
                    json.dump({}, file)
            # This loads the data into the variable dict called loaded_data
            with open('contact_book.json', 'r') as file:
                loaded_data = json.load(file)
                for k, v in new_contacts.items():
                    loaded_data[k] = v
            # redumps your data into the json file
            with open('contact_book.json', 'w') as file:
                json.dump(loaded_data, file, indent=4)
            break

contacts()

Just updated a bit of the else part of your code.刚刚更新了代码的其他部分。 It checks whether a file exists or not .它检查文件是否存在 If it exists, the contents of the file is read and updated and then dumped into the file.如果存在,则读取并更新文件的内容,然后将其转储到文件中。 If it doesn't exist, your old code will be executing.如果它不存在,您的旧代码将被执行。

if os.stat("contact_book.json").st_size != 0:
    with open('contact_book.json', 'r+') as file:
        contents = json.loads(file.read())
        contents.update(new_contacts)
        file.seek(0)
        json.dump(contents, file, indent=4)
else:
        with open('contact_book.json', 'a') as file:
        json.dump(new_contacts, file, indent=4)
        break

Honestly, not an efficient solution.老实说,这不是一个有效的解决方案。 But this should be able to invoke an idea.但这应该能够调用一个想法。

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

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