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

如何为Python的data_manager类新增从JSON指定base提取值的功能

实现方案

直接在现有data_manager类中新增get_value实例方法即可,具体实现如下:

新增的方法代码

你可以直接将这段代码添加到data_manager类的内部即可:

def get_value(self, key, base, default=None):
    # 先校验base节点是否存在
    if base not in self.collection:
        return default
    # 从base节点下取对应key的值,不存在返回默认值
    return self.collection[base].get(key, default)

方法逻辑说明:

  • 参数顺序完全匹配你要求的get_value(key, base)调用形式
  • 内置异常兼容:当指定的base节点不存在、或base节点下不存在对应key时,默认返回None,你也可以调用时传入第三个参数自定义默认返回值
  • 读取的是已经加载到内存的self.collection数据,不需要重复读磁盘,性能更高

完整更新后的类代码

import json
import os

class data_manager():
    BASE_COLLECTIONS_FOLDER = "./data"

    def __init__(self, collection_name):
        self.collection_name = collection_name
        self.collection_file_path = (
                        f"{self.BASE_COLLECTIONS_FOLDER}/{self.collection_name}.json")
        self.collection = {}
        self.ensure_collection()
        self.load_collection()

    def ensure_collection(self):
        if os.path.isfile(self.collection_file_path):
            return

        os.makedirs(self.BASE_COLLECTIONS_FOLDER, exist_ok=True)
        self.save_collection()

    def load_collection(self):
        with open(self.collection_file_path, "r", encoding="utf-8") as collection_file:
            self.collection = json.load(collection_file)[self.collection_name]

    def save_collection(self):
        with open(self.collection_file_path, "w", encoding="utf-8") as collection_file:
            json.dump({self.collection_name: self.collection}, collection_file, indent=4)

    def write_to_json(self, data, key=None):
        if not key:
            self.collection = {**self.collection, **data}
        else:
            self.collection[key] = {**self.collection.get(key, {}), **data}
        self.save_collection()
    
    # 新增的取值方法
    def get_value(self, key, base, default=None):
        if base not in self.collection:
            return default
        return self.collection[base].get(key, default)

调用测试示例

# 初始化集合实例
people = data_manager("twitch")
# 按你要求的形式调用取值
res = people.get_value('streamer_title','mizkif')
print(res)
# 输出结果:(DAY 2) NNN  - WHO WAS IN MY ROOM LAST NIGHT? MARIO PARTY LATER  | !pobox

# 自定义默认返回值示例
res2 = people.get_value('not_exist_key','not_exist_base', default='查询结果不存在')
print(res2)
# 输出结果:查询结果不存在

内容的提问来源于stack exchange,提问作者John Anthony

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:36:03