jsonref

jsonref is a library for automatic dereferencing of JSON Reference objects for Python (supporting Python 2.6+ and Python 3.3+).

from pprint import pprint
from jsonref import JsonRef

# Sample JSON data, like from json.load
document = {
    "data": ["a", "b", "c"],
    "reference": {"$ref": "#/data/1"}
}

# The JsonRef.replace_refs class method will return a copy of the document
# with refs replaced by :class:`JsonRef` objects
pprint(JsonRef.replace_refs(document))
{'data': ['a', 'b', 'c'], 'reference': 'b'}

JsonRef Objects

JsonRef objects are used to replace the JSON reference objects within the data structure. They act as proxies to whatever data the reference is pointing to, but only look up that data the first time they are accessed. Once JSON reference objects have been substituted in your data structure, you can use the data as if it does not contain references at all.

The primary interface to use JsonRef objects is with the class method JsonRef.replace_refs(). It will return a copy of an object you pass it, with all JSON references contained replaced by JsonRef objects. There are several other options you can pass, seen below.

class jsonref.JsonRef(refobj, base_uri=None, loader=None, jsonschema=False, load_on_repr=True)[source]

A lazy loading proxy to the dereferenced data pointed to by a JSON Reference object.

classmethod replace_refs(obj, base_uri=None, loader=None, jsonschema=False, load_on_repr=True)[source]

Returns a deep copy of obj with all contained JSON reference objects replaced with JsonRef instances.

Parameters:
  • obj – If this is a JSON reference object, a JsonRef instance will be created. If obj is not a JSON reference object, a deep copy of it will be created with all contained JSON reference objects replaced by JsonRef instances
  • base_uri – URI to resolve relative references against
  • loader – Callable that takes a URI and returns the parsed JSON (defaults to global jsonloader, a JsonLoader instance)
  • jsonschema – Flag to turn on JSON Schema mode. ‘id’ keyword changes the base_uri for references contained within the object
  • load_on_repr – If set to False, repr() call on a JsonRef object will not cause the reference to be loaded if it hasn’t already. (defaults to True)

JsonRef instances proxy almost all operators and attributes to the referent data, which will be loaded when first accessed. The following attributes are not proxied:

__subject__

Contains the referent data. Accessing this will cause the data to be loaded if it has not already been.

__reference__

Contains the original JSON Reference object. Accessing this attribute will not cause the referent data to be loaded.

Loading a document at a given URI

In order to actually get and parse the JSON at a given URI, JsonRef objects pass the URI to a callable, set with the keyword argument loader. This callable must take the URI as an argument, and return the parsed JSON referred to by that URI.

The JsonLoader class is provided to fill this role, and a default instance of it will be used for all refs unless a custom one is specified.

class jsonref.JsonLoader(store=(), cache_results=True)[source]

Provides a callable which takes a URI, and returns the loaded JSON referred to by that URI. Uses requests if available for HTTP URIs, and falls back to urllib. By default it keeps a cache of previously loaded documents.

Parameters:
  • store – A pre-populated dictionary matching URIs to loaded JSON documents
  • cache_results – If this is set to false, the internal cache of loaded JSON documents is not used
__call__(uri, **kwargs)[source]

Return the loaded JSON referred to by uri

Parameters:
  • uri – The URI of the JSON document to load
  • kwargs – Keyword arguments passed to json.loads()

json module drop in replacement functions

Several functions are provided as drop in replacements to functions from the json module.

load

load() and loads() work just like their json counterparts, except for references will already be replaced in the return values.

jsonref.load(fp, base_uri='', loader=None, jsonschema=False, load_on_repr=True, **kwargs)[source]

Drop in replacement for json.load(), where JSON references are proxied to their referent data.

Parameters:
  • fp – File-like object containing JSON document
  • kwargs – This function takes any of the keyword arguments from JsonRef.replace_refs(). Any other keyword arguments will be passed to json.load()
jsonref.loads(s, base_uri='', loader=None, jsonschema=False, load_on_repr=True, **kwargs)[source]

Drop in replacement for json.loads(), where JSON references are proxied to their referent data.

Parameters:
  • s – String containing JSON document
  • kwargs – This function takes any of the keyword arguments from JsonRef.replace_refs(). Any other keyword arguments will be passed to json.loads()

There is also a convenience function provided to load and process references on a document at a given uri using the specified loader

jsonref.load_uri(uri, base_uri=None, loader=None, jsonschema=False, load_on_repr=True)[source]

Load JSON data from uri with JSON references proxied to their referent data.

Parameters:
  • uri – URI to fetch the JSON from
  • kwargs – This function takes any of the keyword arguments from JsonRef.replace_refs()

dump

dump() and dumps() work just like their json counterparts, except they output the original reference objects when encountering JsonRef instances.

jsonref.dump(obj, fp, **kwargs)[source]

Serialize obj, which may contain JsonRef objects, as a JSON formatted stream to file-like fp. JsonRef objects will be dumped as the original reference object they were created from.

Parameters:
  • obj – Object to serialize
  • fp – File-like to output JSON string
  • kwargs – Keyword arguments are the same as to json.dump()
jsonref.dumps(obj, **kwargs)[source]

Serialize obj, which may contain JsonRef objects, to a JSON formatted string. JsonRef objects will be dumped as the original reference object they were created from.

Parameters:
  • obj – Object to serialize
  • kwargs – Keyword arguments are the same as to json.dumps()