ragraph.io.json#

JSON encoding/decoding support.

Module Contents#

Classes#

GraphEncoder

Extensible JSON <http://json.org> encoder for Python data structures.

Functions#

graph_from_json_dict(→ ragraph.graph.Graph)

Recreate Graph object from JSON dictionary.

from_json(→ ragraph.graph.Graph)

Decode JSON file or string into a Graph.

to_json(→ Optional[str])

Encode Graph to JSON file or string.

class ragraph.io.json.GraphEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)#

Bases: json.JSONEncoder

Extensible JSON <http://json.org> encoder for Python data structures.

Supports the following objects and types by default:

Python

JSON

dict

object

list, tuple

array

str

string

int, float

number

True

true

False

false

None

null

To extend this to recognize other objects, subclass and implement a .default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).

default(obj)#

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
ragraph.io.json.graph_from_json_dict(graph_dict: Dict[str, Any], use_uuid: bool = True) ragraph.graph.Graph#

Recreate Graph object from JSON dictionary.

ragraph.io.json.from_json(path: Optional[Union[str, pathlib.Path]] = None, enc: Optional[str] = None, use_uuid: bool = True) ragraph.graph.Graph#

Decode JSON file or string into a Graph.

Parameters:
  • path – JSON file path.

  • enc – JSON encoded string.

Returns:

Graph object.

ragraph.io.json.to_json(graph: ragraph.graph.Graph, path: Optional[Union[str, pathlib.Path]] = None) Optional[str]#

Encode Graph to JSON file or string.

Parameters:

path – Optional file path to write JSON to.

Returns:

JSON string.