File size: 982 Bytes
105b369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
27
28
29
30
31
import json
from datetime import datetime, date
from pathlib import Path
from typing import Optional, Dict, Union, List

from phi.utils.log import logger


class CustomJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime) or isinstance(o, date):
            return o.isoformat()

        if isinstance(o, Path):
            return str(o)

        return json.JSONEncoder.default(self, o)


def read_json_file(file_path: Optional[Path]) -> Optional[Union[Dict, List]]:
    if file_path is not None and file_path.exists() and file_path.is_file():
        logger.debug(f"Reading {file_path}")
        return json.loads(file_path.read_text())
    return None


def write_json_file(file_path: Optional[Path], data: Optional[Union[Dict, List]], **kwargs) -> None:
    if file_path is not None and data is not None:
        logger.debug(f"Writing {file_path}")
        file_path.write_text(json.dumps(data, cls=CustomJSONEncoder, indent=4, **kwargs))