Skip to content

2025 01 02 #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]

### Added

- Cache results of processing. Repeated calls to get methods will be faster.
- Can process dependentSchemas keyword
- Can process if / then / else keywords

### Removed

Expand Down
48 changes: 35 additions & 13 deletions compiletojsonschema/compiletojsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,23 @@ def __init__(
self.codelist_base_directory = os.path.expanduser(codelist_base_directory)
else:
self.codelist_base_directory = os.getcwd()
# These vars hold output
self._processed = False
self._output_json = None

def get(self):
self.__process()
return self._output_json

def get_as_string(self):
return json.dumps(self.get(), indent=2)

def __process(self):
# If already processed, return .....
if self._processed:
return

# Process now ....
if self.input_filename:
with open(self.input_filename) as fp:
resolved = jsonref.load(
Expand All @@ -42,15 +57,10 @@ def get(self):
resolved = jsonref.JsonRef.replace_refs(self.input_schema)
else:
raise Exception("Must pass input_filename or input_schema")
self._output_json = self.__process_data(resolved)
self._processed = True

resolved = self.__process(resolved)

return resolved

def get_as_string(self):
return json.dumps(self.get(), indent=2)

def __process(self, source):
def __process_data(self, source):

out = deepcopy(source)

Expand All @@ -61,24 +71,36 @@ def __process(self, source):

if "properties" in source:
for leaf in list(source["properties"]):
out["properties"][leaf] = self.__process(source["properties"][leaf])
out["properties"][leaf] = self.__process_data(
source["properties"][leaf]
)
if self.set_additional_properties_false_everywhere:
out["additionalProperties"] = False

if "items" in source:
out["items"] = self.__process(source["items"])
out["items"] = self.__process_data(source["items"])

if "oneOf" in source:
for idx, data in enumerate(list(source["oneOf"])):
out["oneOf"][idx] = self.__process(source["oneOf"][idx])
out["oneOf"][idx] = self.__process_data(source["oneOf"][idx])

if "anyOf" in source:
for idx, data in enumerate(list(source["anyOf"])):
out["anyOf"][idx] = self.__process(source["anyOf"][idx])
out["anyOf"][idx] = self.__process_data(source["anyOf"][idx])

if "allOf" in source:
for idx, data in enumerate(list(source["allOf"])):
out["allOf"][idx] = self.__process(source["allOf"][idx])
out["allOf"][idx] = self.__process_data(source["allOf"][idx])

if "dependentSchemas" in source and isinstance(
source["dependentSchemas"], dict
):
for k, v in source["dependentSchemas"].items():
out["dependentSchemas"][k] = self.__process_data(v)

for keyword in ["if", "then", "else"]:
if keyword in source:
out[keyword] = self.__process_data(source[keyword])

if "codelist" in source and (
"openCodelist" not in source or not source["openCodelist"]
Expand Down
19 changes: 19 additions & 0 deletions tests/fixtures/simple/file-dependentSchemas.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"type": "object",
"properties": {
"credit_card": {
"type": "number"
}
},
"dependentSchemas": {
"credit_card": {
"properties": {
"address": {
"$ref": "file-definitions.json#/definition/address",
"title": "Credit card number (with optional address elements)"
}
},
"required": ["address"]
}
}
}
33 changes: 33 additions & 0 deletions tests/fixtures/simple/file-if-then-else.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
"credit_card": {
"type": "string"
}
},
"if": {
"properties": {
"credit_card": {
"pattern": "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"
}
}
},
"then": {
"properties": {
"address": {
"$ref": "file-definitions.json#/definition/address",
"title": "Must have an address with a credit card"
}
},
"required": ["address"]
},
"else": {
"properties": {
"cash_on_delivery": { "const": "Yup" }
},
"required": ["cash_on_delivery"]
}
}
36 changes: 36 additions & 0 deletions tests/test_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,39 @@ def test_file_list_allof():
def test_passing_empty_schema_is_ok():
ctjs = CompileToJsonSchema(input_schema={})
assert "{}" == ctjs.get_as_string()


def test_file_dependentSchemas():

input_filename = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"fixtures",
"simple",
"file-dependentSchemas.json",
)

ctjs = CompileToJsonSchema(input_filename=input_filename)
out = ctjs.get()

assert (
out["dependentSchemas"]["credit_card"]["properties"]["address"]["title"]
== "Credit card number (with optional address elements)"
)


def test_file_if_then_else():

input_filename = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"fixtures",
"simple",
"file-if-then-else.json",
)

ctjs = CompileToJsonSchema(input_filename=input_filename)
out = ctjs.get()

assert (
out["then"]["properties"]["address"]["title"]
== "Must have an address with a credit card"
)
Loading