Skip to content

DeserializationError: Invalid type: "decimal.Decimal" #185

@bziolo-dtiq

Description

@bziolo-dtiq

Hey there,

When "deserializating" a dictionary that contains a decimal.Decimal field, to a class that accepts that field as an int or a float, JSONS is throwing an exception:

Traceback (most recent call last):
  File "testing-ground/decimal_jsons_test.py", line 19, in <module>
    a = jsons.load(dictionary, Something)
  File "testing-ground/env/lib/python3.10/site-packages/jsons/_load_impl.py", line 101, in load
    return _do_load(json_obj, deserializer, cls, initial, **kwargs_)
  File "testing-ground/env/lib/python3.10/site-packages/jsons/_load_impl.py", line 113, in _do_load
    result = deserializer(json_obj, cls, **kwargs)
  File "testing-ground/env/lib/python3.10/site-packages/jsons/deserializers/default_object.py", line 40, in default_object_deserializer
    constructor_args = _get_constructor_args(obj, cls, **kwargs)
  File "testing-ground/env/lib/python3.10/site-packages/jsons/deserializers/default_object.py", line 64, in _get_constructor_args
    key, value = _get_value_for_attr(obj=obj,
  File "testing-ground/env/lib/python3.10/site-packages/jsons/deserializers/default_object.py", line 94, in _get_value_for_attr
    result = sig_key, _get_value_from_obj(obj, cls, sig, sig_key,
  File "testing-ground/env/lib/python3.10/site-packages/jsons/deserializers/default_object.py", line 140, in _get_value_from_obj
    value = load(obj[sig_key], cls_, meta_hints=new_hints, **kwargs)
  File "testing-ground/env/lib/python3.10/site-packages/jsons/_load_impl.py", line 83, in load
    cls, meta_hints = _check_and_get_cls_and_meta_hints(
  File "testing-ground/env/lib/python3.10/site-packages/jsons/_load_impl.py", line 200, in _check_and_get_cls_and_meta_hints
    raise DeserializationError(msg, json_obj, cls)
jsons.exceptions.DeserializationError: Invalid type: "decimal.Decimal", only arguments of the following types are allowed: str, int, float, bool, list, tuple, set, dict, NoneType

But JSONS is capable of deserializing this dictionary just fine, we just need to modify the list of types it is supposed to be able to deserialize, here, we just need to add decimal.Decimal to the list of VALID_TYPES

For this code:

import jsons
from decimal import Decimal
from dataclasses import dataclass

dictionary = {
    'value': Decimal(15.0)
}

@dataclass
class Something:
    value: float

a = jsons.load(dictionary, Something)
print(a.value)

Observed behavior:
Jsons throws the above exception

Expected behavior:
a.value is initialized to 15.0

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions