# -*- coding: utf-8 -*-""" Operators for json file and directory. """importjsonimportosfromtypingimportAnyfromagentscope.service.service_responseimportServiceResponsefromagentscope.service.service_statusimportServiceExecStatus
[docs]defread_json_file(file_path:str)->ServiceResponse:""" Read and parse a JSON file. Args: file_path (`str`): The path to the JSON file to be read. Returns: `ServiceResponse`: Where the boolean indicates success, the Any is the parsed JSON content (typically a dict), and the str contains an error message if any, including the error type. """try:withopen(file_path,"r",encoding="utf-8")asfile:returnServiceResponse(status=ServiceExecStatus.SUCCESS,content=f"{json.load(file)}",)exceptExceptionase:error_message=f"{e.__class__.__name__}: {e}"returnServiceResponse(status=ServiceExecStatus.ERROR,content=error_message,)
[docs]defwrite_json_file(file_path:str,data:Any,overwrite:bool=False,)->ServiceResponse:""" Serialize data to a JSON file. Args: file_path (`str`): The path to the file where the JSON data will be written. data (`Any`): The data to serialize to JSON. overwrite (`bool`): Whether to overwrite the file if it already exists. Returns: `ServiceResponse`: where the boolean indicates success, and the str contains an error message if any, including the error type. """ifnotoverwriteandos.path.exists(file_path):returnServiceResponse(status=ServiceExecStatus.ERROR,content="FileExistsError: The file already exists.",)try:withopen(file_path,"w",encoding="utf-8")asfile:json.dump(data,file,ensure_ascii=False,indent=4)returnServiceResponse(status=ServiceExecStatus.SUCCESS,content="Success",)exceptExceptionase:error_message=f"{e.__class__.__name__}: {e}"returnServiceResponse(status=ServiceExecStatus.ERROR,content=error_message,)