You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现JSON数据库的数据插入与数组更新?

Python 实现小型JSON数据库的合法结构与操作方案

JSON语法不允许同一层级出现重复键,所以首先得把数据改成合法格式,下面提供两种常用的合法结构及对应操作代码:

方案1:用用户邮箱作为唯一键的字典(推荐,查找效率高)

这种结构以用户邮箱为键,每个用户的信息包含密码和Two数组,完全符合JSON规范,且操作方便:

{
  "Daniel.Michaelson@outlook.com": {
    "password": "1234567",
    "Two": []
  },
  "Matt.Demon@outlook.com": {
    "password": "your_password",
    "Two": ["existing_element"]
  }
}

操作代码

import json
import os

# 定义数据库文件路径
DB_FILE = "user_database.json"

def load_database():
    # 加载数据库,不存在则返回空字典
    if not os.path.exists(DB_FILE):
        return {}
    with open(DB_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_database(db_data):
    # 保存数据库到文件
    with open(DB_FILE, "w", encoding="utf-8") as f:
        json.dump(db_data, f, indent=2)

# 1. 插入包含"One"和空数组"Two"的新条目
def insert_new_user(one_field_value):
    db = load_database()
    # 拆分邮箱和密码(假设One字段格式为"邮箱:密码")
    email, password = one_field_value.split(":", 1)
    if email in db:
        print("该用户已存在,无需重复插入")
        return
    # 添加新用户,Two字段设为空数组
    db[email] = {
        "password": password,
        "Two": []
    }
    save_database(db)
    print("新条目插入成功")

# 调用示例:插入Daniel的条目
insert_new_user("Daniel.Michaelson@outlook.com:1234567")

# 2. 为Matt的"Two"数组添加元素
def add_element_to_user_two(email, new_element):
    db = load_database()
    if email not in db:
        print("未找到该用户")
        return
    # 确保Two字段是数组类型
    if not isinstance(db[email]["Two"], list):
        print("该用户的Two字段不是数组,无法添加元素")
        return
    db[email]["Two"].append(new_element)
    save_database(db)
    print("元素已成功添加到Two数组")

# 调用示例:给Matt的Two数组加元素
add_element_to_user_two("Matt.Demon@outlook.com", "new_item_123")

方案2:用数组存储用户条目(保留原字段结构)

如果需要保留每个条目包含One和Two的结构,可以用数组存储所有条目,同样符合JSON规范:

[
  {
    "One": "Daniel.Michaelson@outlook.com:1234567",
    "Two": []
  },
  {
    "One": "Matt.Demon@outlook.com:your_password",
    "Two": ["existing_element"]
  }
]

操作代码

import json
import os

DB_FILE = "user_database.json"

def load_database():
    if not os.path.exists(DB_FILE):
        return []
    with open(DB_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_database(db_data):
    with open(DB_FILE, "w", encoding="utf-8") as f:
        json.dump(db_data, f, indent=2)

# 1. 插入新条目
def insert_new_entry(one_field_value):
    db = load_database()
    # 检查是否已存在相同One值的条目
    for entry in db:
        if entry.get("One") == one_field_value:
            print("该条目已存在")
            return
    db.append({
        "One": one_field_value,
        "Two": []
    })
    save_database(db)
    print("新条目插入成功")

insert_new_entry("Daniel.Michaelson@outlook.com:1234567")

# 2. 为Matt的Two数组添加元素
def add_element_to_two(target_email, new_element):
    db = load_database()
    entry_found = False
    for entry in db:
        one_value = entry.get("One")
        # 匹配One字段中的邮箱
        if one_value and target_email in one_value:
            if not isinstance(entry["Two"], list):
                print("该条目的Two字段不是数组")
                return
            entry["Two"].append(new_element)
            entry_found = True
            break
    if not entry_found:
        print("未找到对应用户的条目")
        return
    save_database(db)
    print("元素添加成功")

add_element_to_two("Matt.Demon@outlook.com", "new_item_123")

内容的提问来源于stack exchange,提问作者big wanga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:22:06