Skip to content

Commit

Permalink
Accept numbers serialized as strings
Browse files Browse the repository at this point in the history
Updates `deserialize` to accept numeric values encoded as strings. 

This occurs when JSON serialization a dictionary with `int` or `float` keys. To handle a dictionary, JSON converts the value into an object. Objects must have string-valued keys, so the numbers are encoded i.e. `str(x)` for any `x` that is a dictionary key.

The updated final deserialization case now attempts to perform this specific deserialization route before testing the existing numerical deserialization routes. New test cases are present to check for this new behavior.
  • Loading branch information
malcolmgreaves committed Mar 9, 2022
1 parent 5d0f77d commit 9cdc59f
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion core_utils/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,15 +210,25 @@ def deserialize(
return type_value[value] # type: ignore

else:

# Check to see that the expected value is present & has the expected type,
# iff the expected type is one of JSON's value types.
if (
(value is None and not _is_optional(checking_type_value))
or (any(map(lambda t: t == type_value, (int, float, str, bool))))
and not isinstance(value, checking_type_value)
):
fail = False
# exception: encoded a number into a string; attempt trivial decoding to avoid failure
# JSON will encode numbers that are dictionary keys as strings
# so that it can make them compliant as objects.
if issubclass(checking_type_value, Number) and isinstance(value, str):
try:
value = type_value(value.strip())
except ValueError:
fail = True
# numeric check: some ints can be a float
if (
elif (
float == type_value
and isinstance(value, int)
and int(float(value)) == value
Expand All @@ -230,6 +240,9 @@ def deserialize(
# but in general we just identified a value that
# didn't deserialize to its expected type
else:
fail = True

if fail:
raise FieldDeserializeFail(
field_name="", expected_type=type_value, actual_value=value
)
Expand Down

0 comments on commit 9cdc59f

Please sign in to comment.