如何使用以下現有解決方案獲取存盤在特定基礎/類別下的 JSON 檔案中的變數的值?
這是一個接受 JSON 并將其存盤在最初來自Multipurpose 函式的集合中的類,以 使用指定的基礎 python 創建和附加 json
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()
people = data_manager("twitch")
streamer_information = {'streamer_username':None, 'streamer_username': None,
'streamer_game': None, 'streamer_uptime': None,
'streamer_viewers': None}
self.data.write_to_json({self.streamer_username: {}})
self.data.write_to_json(
{"online": self.online,
"streamer_title": self.streamer_information['streamer_title'],
"streamer_game": self.streamer_information['streamer_game'],
"streamer_uptime": self.streamer_information['streamer_uptime'],
"streamer_viewers": self.streamer_information['streamer_viewers']},
self.streamer_username)
例如,我的 JSON 檔案如下所示:
{
"twitch": {
"trainwreckstv": {
"online": true,
"streamer_title": "18 give us 1 f'in w ffs #ad | !twitter | !youtube | !podcast",
"streamer_game": "Slots",
"streamer_uptime": "18:40:53",
"streamer_viewers": "24,922"
},
"mizkif": {
"online": true,
"streamer_title": "(DAY 2) NNN - WHO WAS IN MY ROOM LAST NIGHT? MARIO PARTY LATER | !pobox",
"streamer_game": "Just Chatting",
"streamer_uptime": "4:39:47",
"streamer_viewers": "45,400"
}
}
}
我如何獲得"streamer_title"從特定基礎(例如mizkif或trainwreckstv)開始的價值?
如果我可以做people.get_value(key, base)
where key is thekey并且base是開始搜索的類別,那就太好
了。
例如:
people.get_value('streamer_title','mizkif')
可以回傳:
"(DAY 2) NNN - WHO WAS IN MY ROOM LAST NIGHT? MARIO PARTY LATER | !pobox"
uj5u.com熱心網友回復:
要從“mizkif”獲取值“streamer_title”,您需要將 [] 與字典一起使用。
people["mizkif"]["streamer_title"]
uj5u.com熱心網友回復:
這是實作那個“好方法”的方法。
注意我更改了類的名稱以符合PEP 8 命名約定。
import json
import os
class DataManager:
BASE_COLLECTIONS_FOLDER = "./data"
def __init__(self, collection_name):
self.collection_name = collection_name
self.collection_file_path = (
os.path.join(self.BASE_COLLECTIONS_FOLDER, self.collection_name ".json"))
self.collection = {}
self.ensure_collection()
self.load_collection()
def get_value(self, key, base): # ADDED METHOD
return self.collection[self.collection_name][base][key]
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()
if __name__ == '__main__':
people = DataManager("twitch")
print("people.get_value('streamer_title', 'mizkif') ->")
print(f" {people.get_value('streamer_title', 'mizkif')!r}")
輸出:
people.get_value('streamer_title', 'mizkif') ->
'(DAY 2) NNN - WHO WAS IN MY ROOM LAST NIGHT? MARIO PARTY LATER | !pobox'
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/347711.html
上一篇:添加華為套件時出現“Couldnotfindcom.huawei.hms:location:6.0.0.302”錯誤
