turbo_broccoli.custom.dct
Dicts with non-string keys
1"""Dicts with non-string keys""" 2 3from typing import Any 4 5from turbo_broccoli.context import Context 6from turbo_broccoli.exceptions import DeserializationError, TypeNotSupported 7 8 9def _json_to_dict_v1(dct: dict, ctx: Context) -> dict: 10 return {d["key"]: d["value"] for d in dct["data"]} 11 12 13# pylint: disable=missing-function-docstring 14def from_json(dct: dict, ctx: Context) -> dict: 15 try: 16 decoders = { 17 1: _json_to_dict_v1, 18 } 19 return decoders[dct["__version__"]](dct, ctx) 20 except KeyError as exc: 21 raise DeserializationError() from exc 22 23 24def to_json(obj: Any, ctx: Context) -> dict: 25 """ 26 Serializes a dict with non-string keys. The return dict has the following 27 structure 28 29 ```py 30 { 31 "__type__": "dict", 32 "__version__": 1, 33 "data": [ 34 { 35 "key": ..., 36 "value": ..., 37 }, 38 ... 39 ] 40 } 41 ``` 42 43 where the keys are values are themselves converted to JSON. 44 """ 45 if not ( 46 isinstance(obj, dict) 47 and not all(isinstance(k, str) for k in obj.keys()) 48 ): 49 raise TypeNotSupported() 50 return { 51 "__type__": "dict", 52 "__version__": 1, 53 "data": [{"key": k, "value": v} for k, v in obj.items()], 54 }
25def to_json(obj: Any, ctx: Context) -> dict: 26 """ 27 Serializes a dict with non-string keys. The return dict has the following 28 structure 29 30 ```py 31 { 32 "__type__": "dict", 33 "__version__": 1, 34 "data": [ 35 { 36 "key": ..., 37 "value": ..., 38 }, 39 ... 40 ] 41 } 42 ``` 43 44 where the keys are values are themselves converted to JSON. 45 """ 46 if not ( 47 isinstance(obj, dict) 48 and not all(isinstance(k, str) for k in obj.keys()) 49 ): 50 raise TypeNotSupported() 51 return { 52 "__type__": "dict", 53 "__version__": 1, 54 "data": [{"key": k, "value": v} for k, v in obj.items()], 55 }
Serializes a dict with non-string keys. The return dict has the following structure
{
"__type__": "dict",
"__version__": 1,
"data": [
{
"key": ...,
"value": ...,
},
...
]
}
where the keys are values are themselves converted to JSON.