Coverage for muutils/json_serialize/__init__.py: 0%

6 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-04-04 03:33 -0600

1"""submodule for serializing things to json in a recoverable way 

2 

3you can throw *any* object into `muutils.json_serialize.json_serialize` 

4and it will return a `JSONitem`, meaning a bool, int, float, str, None, list of `JSONitem`s, or a dict mappting to `JSONitem`. 

5 

6The goal of this is if you want to just be able to store something as relatively human-readable JSON, and don't care as much about recovering it, you can throw it into `json_serialize` and it will just work. If you want to do so in a recoverable way, check out [`ZANJ`](https://github.com/mivanit/ZANJ). 

7 

8it will do so by looking in `DEFAULT_HANDLERS`, which will keep it as-is if its already valid, then try to find a `.serialize()` method on the object, and then have a bunch of special cases. You can add handlers by initializing a `JsonSerializer` object and passing a sequence of them to `handlers_pre` 

9 

10additionally, `SerializeableDataclass` is a special kind of dataclass where you specify how to serialize each field, and a `.serialize()` method is automatically added to the class. This is done by using the `serializable_dataclass` decorator, inheriting from `SerializeableDataclass`, and `serializable_field` in place of `dataclasses.field` when defining non-standard fields. 

11 

12This module plays nicely with and is a dependency of the [`ZANJ`](https://github.com/mivanit/ZANJ) library, which extends this to support saving things to disk in a more efficient way than just plain json (arrays are saved as npy files, for example), and automatically detecting how to load saved objects into their original classes. 

13 

14""" 

15 

16from __future__ import annotations 

17 

18from muutils.json_serialize.array import arr_metadata, load_array 

19from muutils.json_serialize.json_serialize import ( 

20 BASE_HANDLERS, 

21 JsonSerializer, 

22 json_serialize, 

23) 

24from muutils.json_serialize.serializable_dataclass import ( 

25 SerializableDataclass, 

26 serializable_dataclass, 

27 serializable_field, 

28) 

29from muutils.json_serialize.util import try_catch, JSONitem, dc_eq 

30 

31__all__ = [ 

32 # submodules 

33 "array", 

34 "json_serialize", 

35 "serializable_dataclass", 

36 "serializable_field", 

37 "util", 

38 # imports 

39 "arr_metadata", 

40 "load_array", 

41 "BASE_HANDLERS", 

42 "JSONitem", 

43 "JsonSerializer", 

44 "json_serialize", 

45 "try_catch", 

46 "JSONitem", 

47 "dc_eq", 

48 "serializable_dataclass", 

49 "serializable_field", 

50 "SerializableDataclass", 

51]