Skip to content

Commit 330376f

Browse files
committed
Created data.json.is_valid()
1 parent c114ed6 commit 330376f

2 files changed

Lines changed: 32 additions & 0 deletions

File tree

  • remove-json-keys/src/remove_json_keys/lib/data
  • translate-messages/src/translate_messages/lib/data

remove-json-keys/src/remove_json_keys/lib/data/json.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,22 @@
55

66
from . import file
77

8+
def is_valid(file_path, format='json'):
9+
file_path = Path(file_path)
10+
if not file_path.exists():
11+
return False
12+
try : file_text = file_path.read_text(encoding='utf-8')
13+
except UnicodeDecodeError:
14+
return False
15+
if format == 'json':
16+
try : json.loads(file_text) ; return True
17+
except Exception : return False
18+
elif format == 'json5':
19+
try : json5.loads(file_text) ; return True
20+
except Exception : return False
21+
else:
22+
raise ValueError(f"Unsupported format '{format}'. Expected 'json' or 'json5'.")
23+
824
def read(file_path, encoding='utf-8'):
925
with open(file_path, 'r', encoding=encoding) as file:
1026
return json5.load(file)

translate-messages/src/translate_messages/lib/data/json.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,22 @@
33

44
import json5
55

6+
def is_valid(file_path, format='json'):
7+
file_path = Path(file_path)
8+
if not file_path.exists():
9+
return False
10+
try : file_text = file_path.read_text(encoding='utf-8')
11+
except UnicodeDecodeError:
12+
return False
13+
if format == 'json':
14+
try : json.loads(file_text) ; return True
15+
except Exception : return False
16+
elif format == 'json5':
17+
try : json5.loads(file_text) ; return True
18+
except Exception : return False
19+
else:
20+
raise ValueError(f"Unsupported format '{format}'. Expected 'json' or 'json5'.")
21+
622
def read(file_path, encoding='utf-8'):
723
with open(file_path, 'r', encoding=encoding) as file:
824
return json5.load(file)

0 commit comments

Comments
 (0)