Serialize value to json-convertible object Ensures that all components of value can be serialized to json :param value: object to be serialized
(value)
| 59 | |
| 60 | |
| 61 | def serialize(value): |
| 62 | """ |
| 63 | Serialize value to json-convertible object |
| 64 | Ensures that all components of value can be serialized to json |
| 65 | :param value: object to be serialized |
| 66 | """ |
| 67 | def _serialize(val, _): |
| 68 | if val is None: |
| 69 | return val |
| 70 | if isinstance(val, six.string_types) or isinstance(val, bytes): |
| 71 | return tools.to_utf8(val) |
| 72 | if isinstance(val, enum.Enum): |
| 73 | return str(val) |
| 74 | if isinstance(val, six.integer_types) or type(val) in [float, bool]: |
| 75 | return val |
| 76 | if is_external(val): |
| 77 | return dict(val) |
| 78 | if isinstance(val, (date, datetime)): |
| 79 | return repr(val) |
| 80 | if is_coroutine(val): |
| 81 | return None |
| 82 | raise ValueError("Cannot serialize value '{}' of type {}".format(val, type(val))) |
| 83 | return apply(_serialize, value, apply_to_keys=True) |
| 84 | |
| 85 | |
| 86 | def is_external(value): |