JSON Ref Dict
json-ref-dict is a Python dict-like object that abstracts the resolution of JSONSchema references. It allows lazy loading of referenced documents, supporting both local filesystem and remote HTTP/HTTPS references. The library is currently at version 0.7.2 and maintains an active release cadence with frequent updates.
Warnings
- breaking The internal attribute for accessing the original JSON reference object was renamed from `__json_ref__` to `__reference__` to align with the `jsonref` library conventions.
- breaking `RefDict` no longer inherits directly from `dict`, but now from `collections.abc.Mapping`. This changes its behavior regarding mutability and can affect `isinstance` checks. `RefDict` instances are now immutable collections.
- deprecated The `JsonRefDict` alias for `RefDict` has been removed.
Install
-
pip install json-ref-dict
Imports
- RefDict
from json_ref_dict import RefDict
- JsonRefDict
from json_ref_dict import RefDict
Quickstart
import os
from json_ref_dict import RefDict
# Create dummy YAML files for the example
master_yaml_content = """
definitions:
foo:
type: string
local_ref:
$ref: '#/definitions/foo'
remote_ref:
$ref: 'other.yaml#/definitions/bar'
backref:
$ref: 'other.yaml#/definitions/baz'
"""
other_yaml_content = """
definitions:
bar:
type: integer
baz:
$ref: 'master.yaml#/definitions/foo'
"""
with open("master.yaml", "w") as f:
f.write(master_yaml_content)
with open("other.yaml", "w") as f:
f.write(other_yaml_content)
try:
# Initialize RefDict with a reference to a local YAML file and JSON pointer
schema = RefDict("master.yaml#/definitions")
# Accessing elements triggers lazy resolution
print("Type of local_ref:", schema["local_ref"]["type"])
print("Type of remote_ref:", schema["remote_ref"]["type"])
print("Type of backref:", schema["backref"]["type"])
# Materialize the document to a regular dict (optional)
# from json_ref_dict import materialize
# materialized_schema = materialize(schema)
# print("Materialized schema type:", type(materialized_schema))
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Clean up dummy files
os.remove("master.yaml")
os.remove("other.yaml")