File size: 799 Bytes
d0501ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import json
from pathlib import Path
from typing import List, Type, TypeVar
from pydantic import BaseModel

T = TypeVar("T", bound=BaseModel)

DATA_DIR = Path(__file__).resolve().parent.parent / "data"
DATA_DIR.mkdir(exist_ok=True)

def save_to_json(data: List[BaseModel], filename: str):
    path = DATA_DIR / filename
    with path.open("w", encoding="utf-8") as f:
        json.dump([item.model_dump(mode="json") for item in data], f, indent=2, ensure_ascii=False)

def load_from_json(model_class: Type[T], filename: str) -> List[T]:
    path = DATA_DIR / filename
    if not path.exists():
        return []
    with path.open("r", encoding="utf-8") as f:
        try:
            raw = json.load(f)
            return [model_class(**item) for item in raw]
        except:
            return []