Created
October 18, 2017 11:47
-
-
Save ackerleytng/109f8c3eed205b7f1becd8b0300d00c3 to your computer and use it in GitHub Desktop.
Using jsonschema to validate
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
{ | |
"$schema": "http://json-schema.org/draft-04/schema#", | |
"title": "Remotes array", | |
"type": "array", | |
"items": { | |
"title": "Remote", | |
"type": "object", | |
"properties": { | |
"name": { | |
"description": "The name of this remote machine", | |
"type": "string", | |
"pattern": "^[a-z-]+$" | |
}, | |
"ipv4": { | |
"description": "The ipv4 address of this remote machine", | |
"type": "string", | |
"format": "ipv4" | |
}, | |
"ipv6": { | |
"description": "The ipv6 address of this remote machine", | |
"type": "string", | |
"format": "ipv6" | |
} | |
}, | |
"required": ["name", "ipv4"] | |
} | |
} |
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
[ | |
{ | |
"name": "lxd-host", | |
"ipv4": "192.168.1.128" | |
}, | |
{ | |
"name": "pynomator", | |
"ipv4": "192.168.1.133" | |
} | |
] |
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
import os | |
import json | |
import jsonschema | |
script_path = os.path.dirname(os.path.realpath(__file__)) | |
def load_check_json(file_path="~/.config/pylotte/remotes.json"): | |
# Load the schema from this script's directory | |
schema_path = os.path.join(script_path, "remotes-schema.json") | |
with open(schema_path) as f: | |
schema = json.load(f) | |
# Load the remote | |
file_path = os.path.expanduser(file_path) | |
with open(file_path) as f: | |
data = json.load(f) | |
# Validate the data (will raise exception if format fails | |
jsonschema.validate(data, schema, | |
format_checker=jsonschema.FormatChecker()) | |
return data | |
print(load_check_json()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment