Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

Add JSON validation utility function

Merwane Hamadi63d2a1085c2d
diff --git a/autogpt/json_validation/validate_json.py b/autogpt/json_validation/validate_json.py
new file mode 100644
index 0000000000..127fcc17f4
--- /dev/null
+++ b/autogpt/json_validation/validate_json.py
@@ -0,0 +1,30 @@
+import json
+from jsonschema import Draft7Validator
+from autogpt.config import Config
+from autogpt.logs import logger
+
+CFG = Config()
+
+
+def validate_json(json_object: object, schema_name: object) -> object:
+ """
+ :type schema_name: object
+ :param schema_name:
+ :type json_object: object
+ """
+ with open(f"autogpt/json_schemas/{schema_name}.json", "r") as f:
+ schema = json.load(f)
+ validator = Draft7Validator(schema)
+
+ if errors := sorted(validator.iter_errors(json_object), key=lambda e: e.path):
+ logger.error("The JSON object is invalid.")
+ if CFG.debug_mode:
+ logger.error(json.dumps(json_object, indent=4)) # Replace 'json_object' with the variable containing the JSON data
+ logger.error("The following issues were found:")
+
+ for error in errors:
+ logger.error(f"Error: {error.message}")
+ else:
+ print("The JSON object is valid.")
+
+ return json_object