Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fully expanding $ref references in a json schema with Python

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).

like image 995
fuzzyman Avatar asked Nov 01 '17 11:11

fuzzyman


People also ask

What does $Ref mean in JSON 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.

How do you reference another JSON Schema?

$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.

What is $id in JSON Schema?

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" }


2 Answers

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.

like image 175
Laser Avatar answered Nov 15 '22 04:11

Laser


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]}
like image 42
cardamom Avatar answered Nov 15 '22 04:11

cardamom