Json Reference Extraction In Python
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
Solution 1:
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]}
Solution 2:
thanks to @FreshD , who led me towards YAML which can be loaded and dumped just like JSON.
This is how I solved my use case, which was exact substitution to start with, but now also supports inheritance.
$cattest.yamltemplate:&itema:ab:bpi:3.14exact-value:*iteminherited-value:<<:*itema :Ichanged$python-c"from yaml import load; fp = open(\"test.yaml\",\"r\"); print(load(fp))"
{'template': {'a':'a', 'b':'b', 'pi':3.14}, 'exact-value': {'a':'a', 'b':'b', 'pi':3.14}, 'inherited-value': {'a':'I changed', 'b':'b', 'pi':3.14}}
Solution 3:
I never used/saw these references in json, but I know and used the in YAML also for configuration. This is a nice description how to achieve this.
Post a Comment for "Json Reference Extraction In Python"