Skip to content

Commit 18b6e58

Browse files
committed
validators: add yaml parsing based on suffix
"JSON Schema" schemas are not only written in JSON but also in YAML, a popular example is the Linux Kernel[0]. While it is possible to convert any input file from YAML to JSON on the fly[1], the automatic resolving of schema references is not possible. To allow YAML files for the CLI tool of jsonschema, check the file suffix and parse the referenced file as YAML if it ends on `yaml` or `yml`. In case the Python library `pyyaml` is not installed or any other suffix is found, parsing defaults to JSON as before. [0]: https://github.com/torvalds/linux/tree/master/Documentation/devicetree/bindings [1]: #582 (comment) Signed-off-by: Paul Spooren <[email protected]>
1 parent a11ab2b commit 18b6e58

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

jsonschema/tests/test_validators.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1796,3 +1796,6 @@ class _ReallyFakeJSONResponse(object):
17961796

17971797
def json(self):
17981798
return json.loads(self._response)
1799+
1800+
def text(self):
1801+
return self._response

jsonschema/validators.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -837,18 +837,29 @@ def resolve_remote(self, uri):
837837
except ImportError:
838838
requests = None
839839

840+
try:
841+
import yaml
842+
except ImportError:
843+
yaml = None
844+
840845
scheme = urlsplit(uri).scheme
841846

842847
if scheme in self.handlers:
843848
result = self.handlers[scheme](uri)
844-
elif scheme in [u"http", u"https"] and requests:
845-
# Requests has support for detecting the correct encoding of
846-
# json over http
847-
result = requests.get(uri).json()
848849
else:
849-
# Otherwise, pass off to urllib and assume utf-8
850-
with urlopen(uri) as url:
851-
result = json.loads(url.read().decode("utf-8"))
850+
path = urlsplit(uri).path
851+
if scheme in [u"http", u"https"] and requests:
852+
# Requests has support for detecting the correct encoding
853+
received = requests.get(uri).text
854+
else:
855+
# Otherwise, pass off to urllib and assume utf-8
856+
with urlopen(uri) as url:
857+
received = url.read().decode("utf-8")
858+
859+
if path.endswith((".yaml", ".yml")) and yaml:
860+
result = yaml.safe_load(received)
861+
else:
862+
result = json.loads(received)
852863

853864
if self.cache_remote:
854865
self.store[uri] = result

0 commit comments

Comments
 (0)