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