Json is not only useful as a communication tool for APIs, but also may be used as a markup for configuring running programs as initialization.
I encountered the use of references in json schema for the purpose of reuse.
Since json schema is valid json, I had expected the python json library to have the ability to expand references.
$ cat test.json
{
"template":{
"a":"a",
"b":"b",
"pi":3.14
},
"value": { "$ref":"#/template"}
}
python -c "from json import load; fp = open(\"test.json\",\"r\"); print(load(fp))"
{'template': {'a': 'a', 'b': 'b', 'pi': 3.14}, 'value': {'$ref': '#/template'}}
What is the simplest way to expand the references in python, since python dicts cannot point to other parts of themselves (I think)?
The json library does not support references, but jsonref does.
jsonref
is a library for automatic dereferencing of JSON Reference objects for Python (supporting Python 2.6+ and Python 3.3+).
From the docs:
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