We have a fairly large and complex json schema with many includes via $ref references. Ideally using Python and jsonschema I'd like to take those schema and fully expand the references (recursively) to get the full schema.
Output in the form of a dict is fine (the standard data structure that jsonschema uses to represent a schema).
In a JSON schema, a $ref keyword is a JSON Pointer to a schema, or a type or property in a schema. A JSON pointer takes the form of A # B in which: A is the relative path from the current schema to a target schema. If A is empty, the reference is to a type or property in the same schema, an in-schema reference.
$ref. A schema can reference another schema using the $ref keyword. The value of $ref is a URI-reference that is resolved against the schema's Base URI. When evaluating a $ref , an implementation uses the resolved identifier to retrieve the referenced schema and applies that schema to the instance.
Declaring a unique identifier It is also best practice to include an $id property as a unique identifier for each schema. For now, just set it to a URL at a domain you control, for example: { "$id": "http://yourdomain.com/schemas/myschema.json" }
If you check the json documentation.
You will find that circular $ref is not recommended but not prohibited.
So, in this case, it is not possible to fully expand all $ref
But if you sure that you do not have loops in your $ref
I would recommend you to use this repo It has helped me in such situation. Code is really simple so you can change it on your own.
I have tested and can also recommend the following module:
https://github.com/gazpachoking/jsonref
which is on PyPI. The documentation is good, has been very recently maintained (October 2018), and the syntax is such that it is a drop-in replacement for the standard json module:
from the home page:
>>> from pprint import pprint
>>> import jsonref
>>> # An example json document
>>> json_str = """{"real": [1, 2, 3, 4], "ref": {"$ref": "#/real"}}"""
>>> data = jsonref.loads(json_str)
>>> pprint(data) # Reference is not evaluated until here
{'real': [1, 2, 3, 4], 'ref': [1, 2, 3, 4]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With