55"""
66
77from json import loads , dumps
8+ from jsonschema import validate , ValidationError
89from abc import ABC , abstractmethod
910from datetime import datetime
11+ import requests
1012import re
1113import os
1214import tomlkit
@@ -323,6 +325,10 @@ class JSONConfig(FileConfig):
323325 JSON configuration management class.
324326 This class provides methods to load, save, and manage configuration settings in JSON format.
325327 """
328+
329+ def __init__ (self , file_path : str ):
330+ super ().__init__ (file_path )
331+ self .__validate ()
326332
327333 def _to_string (self ) -> str :
328334 """
@@ -341,6 +347,28 @@ def _from_string(self, config_string: str) -> None:
341347 if not isinstance (self ._config , dict ):
342348 raise ValueError ("Invalid JSON format: expected a dictionary." )
343349
350+ def __validate (self ):
351+ """
352+ Validate the configuration against a JSON schema if provided in the config.
353+ The url to the schema must be provided in the "$schema" key of the config (https://json-schema.org/)
354+ """
355+ if "$schema" in self ._config :
356+ schema_url = self ._config ["$schema" ]
357+ try :
358+ response = requests .get (schema_url )
359+ response .raise_for_status ()
360+ schema = response .json ()
361+ validate (instance = self ._config , schema = schema )
362+ except requests .RequestException as e :
363+ raise ValueError (f"Failed to fetch JSON schema from { schema_url } : { e } " ) from None
364+ except ValidationError as e :
365+ raise ValueError (f"Configuration validation against schema failed: { e .message } " ) from None
366+ except Exception as e :
367+ raise ValueError (f"An error occurred during schema validation: { e } " ) from None
368+ _trace ("Configuration validated successfully against schema." )
369+ else :
370+ _trace ("No JSON schema provided for validation." )
371+
344372class TOMLConfig (FileConfig ):
345373 """
346374 TOML configuration management class.
0 commit comments