Python dict-like object which abstracts resolution of JSONSchema references
Slowing down. Last release over 3 years ago, little activity since. Fine for existing code; think twice for a new project.
pip install json-ref-dictJSONSchema Ref Dict
Python dict-like object which abstracts resolution of JSONSchema references.
from json_ref_dict import RefDict
schema = RefDict("https://json-schema.org/draft-07/schema#/")
Nested items containing "$ref" will be resolved lazily when accessed,
meaning the dictionary can be treating as a single, continuous (and
possibly infinite) document.
Remote references are supported, and will be resolved relative to the current document.
If no scheme is provided, it is assumed that the document is present on the local filesystem (see Example below).
If PyYAML is installed, then loading of YAML documents will be supported, otherwise only JSON documents may be loaded.
Example
Given the following related schemas:
master.yaml
definitions:
foo:
type: string
local_ref:
$ref: '#/definitions/foo'
remote_ref:
$ref: 'other.yaml#/definitions/bar'
backref:
$ref: 'other.yaml#/definitions/baz'
other.yaml
definitions:
bar:
type: integer
baz:
$ref: 'master.yaml#/definitions/foo'
We can parse these as a single object as follows:
from json_ref_dict import RefDict
schema = RefDict("master.yaml#/definitions")
print(schema)
>>> {'foo': {'type': 'string'}, 'local_ref': {'$ref': '#/definitions/foo'}, 'remote_ref': {'$ref': 'other.yaml#/definitions/bar'}, 'backref': {'$ref': 'other.yaml#/definitions/baz'}}
print(schema["local_ref"])
>>> {'type': 'string'}
print(schema["remote_ref"])
>>> {'type': 'integer'}
print(schema["backref"])
>>> {'type': 'string'}
Materializing documents
If you don't want the lazy behaviour, and want to get all of the IO out of the way up front, then you can "materialize" the dictionary:
from json_ref_dict import materialize, RefDict
schema = materialize(RefDict("https://json-schema.org/draft-04/schema#/"))
assert isinstance(schema, dict)
A materialized RefDict is just a regular dict, containing a document with all references resolved. This is useful if, for example, you want to cache/persist the entire schema. Be aware that if there are cyclical references in the schema, these will be present on the materialized dictionary.