Skip to content

Make BaseModel.to_dict() return JSON-serializable values (#93)#227

Open
CedricConday wants to merge 1 commit into
XeroAPI:masterfrom
CedricConday:fix/93-to-dict-enum-uuid
Open

Make BaseModel.to_dict() return JSON-serializable values (#93)#227
CedricConday wants to merge 1 commit into
XeroAPI:masterfrom
CedricConday:fix/93-to-dict-enum-uuid

Conversation

@CedricConday

@CedricConday CedricConday commented Jun 30, 2026

Copy link
Copy Markdown

Fixes #93

BaseModel.to_dict() is documented as returning the model properties as a dict, but enum-typed attributes come back as the raw Enum object, so:

json.dumps(journal.to_dict())
# TypeError: Object of type AccountType is not JSON serializable

serialize_to_dict (the singledispatch used by to_dict) has handlers for BaseModel, list, tuple and dict, but none for Enum, so enums fall through the identity default. The same applies to UUID fields (see #161).

Change

Register Enum and UUID handlers on serialize_to_dict (the Enum handler is exactly what was suggested in the issue):

@serialize_to_dict.register(Enum)
def serialize_enum_to_dict(value):
    return value.value


@serialize_to_dict.register(UUID)
def serialize_uuid_to_dict(value):
    return str(value)

Test

Added tests/test_models.py covering enum→value, UUID→string, and that json.dumps(model.to_dict()) no longer raises. The tests fail on master and pass with the fix; existing suite stays green.


AI-assisted, human-reviewed — I'm an AI engineer; I find, fix, and test with AI, then review and verify before opening.

to_dict() returned enum-typed attributes as raw Enum objects (and
UUID-typed attributes as raw UUID objects), so json.dumps(model.to_dict())
raised 'Object of type ... is not JSON serializable'.

Register Enum and UUID handlers on serialize_to_dict so enums serialize to
their .value and UUIDs to their canonical hyphenated string.

Closes XeroAPI#93.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

to_dict generates non serializable object because of enums

1 participant