monty.json module

JSON serialization and deserialization utilities.

exception MSONError[source]

Bases: Exception

Exception class for serialization errors.

class MSONable[source]

Bases: object

This is a mix-in base class specifying an API for msonable objects. MSON is Monty JSON. Essentially, MSONable objects must implement an as_dict method, which must return a json serializable dict and must also support no arguments (though optional arguments to finetune the output is ok), and a from_dict class method that regenerates the object from the dict generated by the as_dict method. The as_dict method should contain the “@module” and “@class” keys which will allow the MontyEncoder to dynamically deserialize the class. E.g.:

d["@module"] = self.__class__.__module__
d["@module"] = self.__class__.__name__

A default implementation is provided in MSONable, which automatically determines if the class already contains self.argname or self._argname attributes for every arg. If so, these will be used for serialization in the dict format. Similarly, the default from_dict will deserialization classes of such form. An example is given below:

class MSONClass(MSONable):

def __init__(self, a, b, c, d=1, **kwargs):
    self.a = a
    self.b = b
    self._c = c
    self._d = d
    self.kwargs = kwargs

For such classes, you merely need to inherit from MSONable and you do not need to implement your own as_dict or from_dict protocol.

New to Monty V2.0.6…. Classes can be redirected to moved implementations by putting in the old fully qualified path and new fully qualified path into .monty.yaml in the home folder

Example: old_module.old_class: new_module.new_class

as_dict() → dict[source]

A JSON serializable dict representation of an object.

classmethod from_dict(d)[source]

d – Dict representation.


MSONable class.

to_json() → str[source]

Returns a json string representation of the MSONable object.


Returns an hash of the current object. This uses a generic but low performance method of converting the object to a dictionary, flattening any nested keys, and then performing a hash on the resulting object

class MontyDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)[source]

Bases: json.decoder.JSONDecoder

A Json Decoder which supports the MSONable API. By default, the decoder attempts to find a module and name associated with a dict. If found, the decoder will generate a Pymatgen as a priority. If that fails, the original decoded dictionary from the string is returned. Note that nested lists and dicts containing pymatgen object will be decoded correctly as well.


# Add it as a cls keyword when using json.load json.loads(json_string, cls=MontyDecoder)

object_hook, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting).

object_pairs_hook, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

parse_float, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.

If strict is false (true is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including '\t' (tab), '\n', '\r' and '\0'.


Overrides decode from JSONDecoder.


s – string




Recursive method to support decoding dicts and lists containing pymatgen objects.

class MontyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

A Json Encoder which supports the MSONable API, plus adds support for numpy arrays, datetime objects, bson ObjectIds (requires bson).


# Add it as a *cls* keyword when using json.dump
json.dumps(object, cls=MontyEncoder)

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

default(o) → dict[source]

Overriding default method for JSON encoding. This method does two things: (a) If an object has a to_dict property, return the to_dict output. (b) If the @module and @class keys are not in the to_dict, add them to the output automatically. If the object has no to_dict property, the default Python json encoder default method is called.


o – Python object.


Python dict representation.

jsanitize(obj, strict=False, allow_bson=False)[source]

This method cleans an input json-like object, either a list or a dict or some sequence, nested or otherwise, by converting all non-string dictionary keys (such as int and float) to strings, and also recursively encodes all objects using Monty’s as_dict() protocol.

  • obj – input json-like object.

  • strict (bool) – This parameters sets the behavior when jsanitize encounters an object it does not understand. If strict is True, jsanitize will try to get the as_dict() attribute of the object. If no such attribute is found, an attribute error will be thrown. If strict is False, jsanitize will simply call str(object) to convert the object to a string representation.

  • allow_bson (bool) – This parameters sets the behavior when jsanitize encounters an bson supported type such as objectid and datetime. If True, such bson types will be ignored, allowing for proper insertion into MongoDb databases.


Sanitized dict that can be json serialized.