Last active
October 3, 2019 09:40
-
-
Save LordShedy/b24831be673bd3a176442f3eded8c116 to your computer and use it in GitHub Desktop.
JSON Loader And Validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
# created by Lord Shedy | |
# version: 1.0.1 | |
import json | |
from jsonschema import validate | |
from datetime import datetime | |
""" | |
a function to load and validate JSON file (if it is JSON valid) | |
expects readable datapath of a JSON file, as a string | |
returns string of the content of the JSON file, if JSON valid, else error message, as a string | |
the validation is based on whether or not the json.loads() function throws exception or not | |
it is not meant as a fully fledged JSON syntax validator! | |
""" | |
def loadJSONfile(dataFilePath: str) -> str: | |
try: | |
f = open(dataFilePath, "r") | |
except: | |
raise Exception("There was some error when loading" + dataFilePath + "!") | |
else: | |
try: | |
dataFileContent = json.loads(f.read()) | |
except: | |
raise Exception(dataFilePath + " is not a valid JSON file!") | |
else: | |
return dataFileContent | |
""" | |
a function to validate JSON file according to the jsonschema library | |
expects valid JSON file path or JSON file content as a string | |
returns whether or not the data file is valid to the schema, as a boolean | |
the schema must be compliant to the schema syntaxt of jsonschema library! | |
""" | |
def validateJSONfile(dataFilePath: str, schemaFilePath: str) -> bool: | |
try: | |
dataFileContent = loadJSONfile(dataFilePath) | |
schemaFileContent = loadJSONfile(schemaFilePath) | |
except: | |
try: | |
validate(instance = dataFilePath, schema = schemaFilePath) | |
except: | |
return 0 | |
else: | |
return 1 | |
else: | |
try: | |
validate(instance = dataFileContent, schema = schemaFileContent) | |
except: | |
return 0 | |
else: | |
return 1 | |
""" | |
a function to load and validate JSON file, it uses two functions above | |
expects valid JSON file as a string and a JSON schema file as a string | |
returns the JSON file content if valid, error message if not valid, as a string | |
""" | |
def loadAndValidateJSONfile(dataFilePath: str, schemaFilePath: str) -> str: | |
dataFile = loadJSONfile(dataFilePath) | |
if validateJSONfile(dataFilePath, schemaFilePath): | |
return dataFile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment