【问题标题】:How do i get a dictionary appended into a list without overlapping the exitsting dictionary json如何在不重叠现有字典 json 的情况下将字典追加到列表中
【发布时间】:2021-12-18 22:36:37
【问题描述】:

我正在使用 Python、JSON 和烧瓶编写代码 我制作了一个函数“make_user():”来从我的表单中获取数据并将其插入到字典中:

users_list = []
@app.route("/makeuser", methods=["post"])
def make_user():
    firstname = f.request.form["firstname"]
    lastname = f.request.form["lastname"]
    username = f.request.form["username"]
    password = f.request.form["pwd"]
    mail = f.request.form["email"]
    car = f.request.form["car"]

    res = {
        "firstname" : firstname,
        "lastname" : lastname,
        "username" : username,
        "password" : password,
        "mail" : mail,
        "car" : car
    }

当我尝试打开我的 json 文件,然后将现有字典添加到 users_list,然后附加表单中的输入,然后将新列表转储到 json 文件时,问题就来了。 这是我的尝试:

file = open("users.json", "r+")
users_list.append(file)

for list_item in users_list:
    users_list.append(res)

json.dump(users_list,file)
file.close

return redirect(url_for("form"))

我想在 json 文件中包含一个列表,其中包含列表项作为字典,如下所示:[{},{},{},{}]

有什么想法可以解决这个问题吗?

【问题讨论】:

  • users.json 是仅在顶层包含 dict 还是 list

标签: python json forms dictionary flask


【解决方案1】:
file = open("users.json", "r+")
users_list.append(file)

file这里不包含users.json的内容。它是打开文件的“句柄”,您可以从中读取数据——或传递给json.load

for list_item in users_list:
    users_list.append(res)

这一点很荒谬。假设您正确加载了 users.json 的内容,这会将 res 附加到每个元素。这不仅不是您想要的,而且不可能,因为每个元素都是一个字典。

由于您要替换文件的内容,因此您需要打开它两次;一次阅读,一次写作。您不能附加到文件,因为这会破坏结构化的 JSON。试试这样的:

with open("users.json") as file:
    users_list = json.load(file)

users_list.append(res)

with open("users.json", "w") as file:
    json.dump(users_list, file)

【讨论】:

  • 这里我得到这个错误代码,debug=True on: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
  • users.json 开头,仅包含[]
  • Niiii​​ice!现在可以了!
【解决方案2】:

您需要load json 文件中的数据。

with open("users.json", "r") as file:
    try:
        users_list = json.load(file) # This should be your saved json structure
    except json.decoder.JSONDecodeError: # in case your file does not contain valid json or is empty
        users_list = []
if isinstance(users_list, dict): # this can be removed if your top level is a list
    users_list = [users_list]
users_list.append(res) # append to the existing list
with open("users.json", "w") as file:
    json.dump(users_list, file) # dump back to file

假设这就是您文件中的内容。

{
    "firstname" : "Martin",
    "lastname" : "Mouse",
    "username" : "mmouse",
    "password" : "hunter9",
    "mail" : "mmouse@dasney.com",
    "car" : "Lambo"
}

json 模块有一个方便的功能,可以从数据中读取您的文件,并一步将其解析为 python 对象。

users_list = json.load(file)

这实质上是在说:

user_list = {
    "firstname" : "Martin",
    "lastname" : "Mouse",
    "username" : "mmouse",
    "password" : "hunter9",
    "mail" : "mmouse@dasney.com",
    "car" : "Lambo"
}

下一步是确保您的顶级是list,如果不是,请这样做。

if isinstance(users_list, dict):
    users_list = [users_list]

所以现在你的结构看起来像这样。

[
    {
        "firstname" : "Martin",
        "lastname" : "Mouse",
        "username" : "mmouse",
        "password" : "hunter9",
        "mail" : "mmouse@dasney.com",
        "car" : "Lambo"
    }
]

此时您可以追加新条目。

users_list.append(res)

现在是这个。

[
    {
        "firstname" : "Martin",
        "lastname" : "Mouse",
        "username" : "mmouse",
        "password" : "hunter9",
        "mail" : "mmouse@dasney.com",
        "car" : "Lambo"
    },
    {
        "firstname" : "Darnold",
        "lastname" : "Duck",
        "username" : "dduck",
        "password" : "hunter10",
        "mail" : "dduck@dasney.com",
        "car" : "Ferrari"
    }

]

最后,转储回文件。

with open("users.json", "w") as file:
    json.dump(users_list, file) # dump back to file

【讨论】:

  • 这可行,但它只是在列表旁边创建一个列表,如下所示:[{},{},{}][{},{},{}][{},{}, {}]
  • 我收到一条错误消息说这是问题所在:users_list = json.load(file) # 这应该是你保存的 json 结构
  • 如果您的文件中的内容无效json,就会发生这种情况。您可以按照@Woodford 的建议从[] 开始。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 2020-08-04
  • 1970-01-01
相关资源
最近更新 更多