Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json reference extraction in python

Tags:

python

json

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

like image 540
Debanjan Basu Avatar asked Oct 18 '18 09:10

Debanjan Basu


Video Answer


1 Answers

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]}
like image 103
Hugues Fontenelle Avatar answered Oct 03 '22 01:10

Hugues Fontenelle