tefra / xsdata

Naive XML & JSON Bindings for python
https://xsdata.readthedocs.io
MIT License
331 stars 60 forks source link

Support of dict types #1072

Open vvmruder opened 2 months ago

vvmruder commented 2 months ago

I encounter a limit Iam curious why it is there.

Assuming the following code:

from dataclasses import dataclass, field
from xsdata.formats.dataclass.parsers import DictDecoder
test_dict = {
    "dict_type": {
        "a": {
            "name": "namea",
            "value": 1
        },
        "b": {
            "name": "nameb",
            "value": 2
        },
        "c": {
            "name": "namec",
            "value": 3
        }
    }
}

@dataclass
class TestMember:
    name: str = field(
        metadata={
            "type": "Element",
            "required": True
        }
    )
    value: int = field(
        metadata={
            "type": "Element",
            "required": True
        }
    )

@dataclass
class Test:
    dict_type: dict[TestMember]

DictDecoder().decode(test_dict, Test)

It will end up with:

xsdata.exceptions.XmlContextError: Error on Test::dict_type: Xml Text does not support typing `dict[__main__.TestMember]`

May I ask, what are the limitations here or for a hint what I did wrong?

tefra commented 2 days ago

The dict type is only supported for xml attributes, there is no other use case when you are working with xml https://xsdata.readthedocs.io/en/latest/models/types/#dict

json on the other hand supports dynamic properties.