Skip to content

[BUG] KeyError thrown when attempting to read camelCase JSON fields and also specifying mm_field #561

@jpermar-sk

Description

@jpermar-sk

Description

I have a dataclass decorated to use camelCase:

# @dataclass_json decorator must come before @dataclass decorator
@dataclass_json(letter_case=LetterCase.CAMEL, undefined=Undefined.EXCLUDE)
@dataclass
class Store:
    open_time: dt.time = field(
        metadata=config(
            encoder=to_time_str,
            decoder=from_time_str,
            letter_case=LetterCase.CAMEL,
            field_name="openTime",
            mm_field=fields.Time(format="%H:%M:%S"), # comment this line for test to pass. however, warnings are printed.
        )
    )

My test to read JSON with camelCase fields passes when the mm_field config is unset. However, it passes with warnings (telling me to set the mm_field):

UserWarning: Unknown type <class 'datetime.time'> at Store.open_time: <class 'datetime.time'> It's advised to pass the correct marshmallow type to mm_field.

On the flip side, with the mm_field set, the test throws KeyError: 'open_time':

ERROR test_dataclasses_error.py - KeyError: 'open_time'

Code snippet that reproduces the issue

File dataclasses_error.py:

import datetime as dt
from dataclasses import dataclass, field

from dataclasses_json import LetterCase, Undefined, config, dataclass_json
from marshmallow import fields

TIME_FORMAT = "%H:%M:%S"


def from_time_str(time_str: str) -> dt.time:
    return dt.datetime.strptime(time_str, TIME_FORMAT).time()


def to_time_str(time: dt.time) -> str:
    return dt.datetime.strftime(TIME_FORMAT)


# @dataclass_json decorator must come before @dataclass decorator
@dataclass_json(letter_case=LetterCase.CAMEL, undefined=Undefined.EXCLUDE)
@dataclass
class Store:
    open_time: dt.time = field(
        metadata=config(
            encoder=to_time_str,
            decoder=from_time_str,
            letter_case=LetterCase.CAMEL,
            field_name="openTime",
            mm_field=fields.Time(format="%H:%M:%S"), # comment this line for test to pass. however, warnings are printed.
        )
    )


LOCATION_INFO_FILE_CONTENTS: str = """
[
    {
        "openTime": "03:00:00"
    }
]
"""

LOCATION_METADATA: list[Store] = Store.schema().loads(
    LOCATION_INFO_FILE_CONTENTS, many=True
)

and the test:

from dataclasses_error import LOCATION_METADATA


def test_store_load():
    assert len(LOCATION_METADATA) == 1

Describe the results you expected

I expect that the JSON is read correctly (camelCase field) without error and when the mm_field is set.

Python version you are using

Python 3.13.3

Environment description

dataclasses-json==0.6.7
marshmallow==3.26.1
pytest==8.3.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions