schrodinger.models.json module¶
This is a module that extends Python’s standard builtin json module. It offers the following additional features:
JsonableClassMixin
, a mixin that helps with creating serializable classes- An extended JSON encoder that can handle classes derived from
JsonableClassMixin
dump
anddumps
functions that use the extended encoder by default.
-
exception
schrodinger.models.json.
JSONDecodeError
¶ Bases:
ValueError
-
exception
schrodinger.models.json.
JSONEncodeError
¶ Bases:
ValueError
-
class
schrodinger.models.json.
JsonableClassMixin
(*args, **kwargs)¶ Bases:
object
A mixin that aids in making a class Jsonable. Users must define
_toJson(self)
and_fromJson(cls, json_dict)
. For example:class Person(JsonableClassMixin, object): def __init__(self, full_name, age): self.full_name = full_name self.age = age def _toJson(self): return {'full_name':self.full_name, 'age':self.age} @classmethod def _fromJson(cls, json_dict): return cls(json_dict['full_name'], json_dict['age'])
Now
dump
anddumps
can encodePerson
:# Encode to a file abe = Person('Abraham Lincoln', 208) with open('abe.json', 'w') as out_file: json.dump(abe, out_file) # Encode to a string abe_json_string = json.dumps(abe)
If you want to decode the json string or file, you’ll have to use
loads
orload
and then feed in the result to your class’ public class methodfromJson()
:# Loading an object from a json file with open('abe.json', 'r') as in_file: abe_json = json.load(in_file) abe = Person.fromJson(abe_json) # Loading an object from a json string abe_json = json.loads(abe_json_string) abe = Person.fromJson(abe_json)
-
toJson
()¶ Create and returns a data structure made up of jsonable items.
-
classmethod
fromJson
(json_dict)¶ A factory method which constructs a new object from a given dict loaded from a json string or file.
Parameters: - json_dict (dict) – A json-loaded dictionary to create an object from.
- copy_dict (bool) – Whether to copy the dict before modifying it. If set
to False, the dict won’t be safe to use in another
fromJson()
call. Defaults to False.
Returns: An instance of this class.
:rtype : cls
Raises: JsonDecodeError – If the json dict is corrupted or invalid.
-
get_version
()¶ Method to get the version of a particular object. Defaults to the current version of mmshare. This class can be overridden for custom versioning behavior.
-
-
schrodinger.models.json.
adapter
(version)¶ This function is a decorator used to define an adapter function that takes in a
json_dict
from an older version of aJsonableClassMixin
and returns it modified such that it can be read in by the version of the class specified by theversion
argument (typically the current version at the time the adapter is written).As a example, imagine we define a simple class:
class Person: # mmshare version: 40000 def __init__(self, full_name): self.full_name = full_name
If, in mmshare version 41000, we split
full_name
into attributesfirst_name
andlast_name
, we could define an adapter like so:class Person: # mmshare version: 41000 def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @json.adapter(version=41000) def _JsonAdapter(self, json_dict): full_name = json_dict.pop(full_name) fname, lname = full_name.split(' ') json_dict['first_name'] = fname json_dict['last_name'] = lname return json_dict
Note
An adapter function only needs to bring the
json_dict
up-to-date with the class at the time that the adapter is written. The next time the class is changed in a way that breaks json decoding, a new adapter function should be added to the class that takes in the previous adapter’s output and makes it compatible with the current class. In this way the json framework can decode any older version by automatically passing it through the appropriate chain of adapter functions.Parameters: version (int, str, or list of str or ints) – The data version to which an older json_dict
will be adapted (typically the current version when the adapter is writte).Raises: TypeError – if version
is not an int, str, or list
-
class
schrodinger.models.json.
JSONEncoder
(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶ Bases:
json.encoder.JSONEncoder
A wrapper around the builtin JSON encoder that automatically encodes objects derived from
JsonableClassMixin
-
default
(obj)¶ Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).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)
-
-
schrodinger.models.json.
dumps
(obj, **kwargs)¶ A wrapper that uses an encoder to automatically encode objects derived from
JsonableClassMixin
.
-
schrodinger.models.json.
dump
(fp, **kwargs)¶ A wrapper that uses an encoder to automatically encode objects derived from
JsonableClassMixin
.