21
21
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
22
THE SOFTWARE.
23
23
"""
24
+
24
25
import json
25
26
import os
26
- import sys
27
27
from dataclasses import dataclass
28
28
from typing import Optional
29
29
30
+ JSON_ERROR_PARSE = 1
31
+ JSON_ERROR_FILE_NOT_FOUND = 2
32
+ JSON_ERROR_FILE_EMPTY = 3
33
+ JSON_ERROR_FILE_SIZE = 4
34
+
30
35
31
36
@dataclass
32
37
class JsonValidation :
33
38
is_valid : bool
34
39
data : Optional [dict ] = None
35
40
error : Optional [str ] = None
41
+ error_code : Optional [int ] = None
36
42
37
43
38
44
def validate_json_file (json_file_path : str ) -> JsonValidation :
@@ -46,12 +52,33 @@ def validate_json_file(json_file_path: str) -> JsonValidation:
46
52
Tuple[bool, str]: A tuple containing a boolean indicating if the file is valid and a message
47
53
"""
48
54
if not json_file_path :
49
- return JsonValidation (is_valid = False , error = ' No JSON file specified' )
55
+ return JsonValidation (is_valid = False , error = " No JSON file specified" )
50
56
if not os .path .isfile (json_file_path ):
51
- return JsonValidation (is_valid = False , error = f'File not found: { json_file_path } ' )
57
+ return JsonValidation (
58
+ is_valid = False ,
59
+ error = f"File not found: { json_file_path } " ,
60
+ error_code = JSON_ERROR_FILE_NOT_FOUND ,
61
+ )
62
+ try :
63
+ if os .stat (json_file_path ).st_size == 0 :
64
+ return JsonValidation (
65
+ is_valid = False ,
66
+ error = f"File is empty: { json_file_path } " ,
67
+ error_code = JSON_ERROR_FILE_EMPTY ,
68
+ )
69
+ except OSError as e :
70
+ return JsonValidation (
71
+ is_valid = False ,
72
+ error = f"Problem checking file size: { json_file_path } : { e } " ,
73
+ error_code = JSON_ERROR_FILE_SIZE ,
74
+ )
52
75
try :
53
76
with open (json_file_path ) as f :
54
77
data = json .load (f )
55
78
return JsonValidation (is_valid = True , data = data )
56
79
except json .JSONDecodeError as e :
57
- return JsonValidation (is_valid = False , error = f'Problem parsing JSON file: "{ json_file_path } ": { e } ' )
80
+ return JsonValidation (
81
+ is_valid = False ,
82
+ error = f'Problem parsing JSON file: "{ json_file_path } ": { e } ' ,
83
+ error_code = JSON_ERROR_PARSE ,
84
+ )
0 commit comments