marker_separation/py/pallete_schema.py

43 lines
1.0 KiB
Python

from jsonschema import validate
from json import dumps, loads
class PalleteSchema :
colors = None
schema = {
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"name" : { "type" : "string" },
"color" : {
"type" : "array",
"items" : { "type" : "number" }
},
"space" : { "type" : "string" }
},
"required" : [ "name", "color", "space" ]
}
}
def __init__ (self, file = None, obj = None):
if file is not None and obj is None:
self.parse_file(file)
elif file is not None and obj is not None :
self.write(file, obj)
else :
print('Not sure what you\'re trying to do here')
def parse_file (self, file) :
with open(file) as f :
self.parse(f.read())
print(f'Parsed pallete file {file}')
def parse (self, jsonstr) :
obj = loads(jsonstr)
validate( instance = obj, schema = self.schema)
self.colors = obj
def write(self, filepath, obj) :
validate( instance = obj, schema = self.schema)
jsonstr = dumps(obj, indent = 4)
with open(filepath, 'w') as outfile :
outfile.write(jsonstr)