import json
from decimal import Decimal

from marshmallow.fields import Field

__all__ = ["StructOfPrimitives"]


class StructOfPrimitives(Field):
    """Make any struct with decimals json-serializible."""

    @staticmethod
    def _json_default(obj):
        if isinstance(obj, Decimal):
            return str(obj)
        raise TypeError

    def _serialize(self, value, *args, **kwargs):
        encoded = json.dumps(value, default=self._json_default)
        return json.loads(encoded)
