Coder Social home page Coder Social logo

Comments (8)

atteneder avatar atteneder commented on May 22, 2024

This work-around does not work on nested member/classes though:

import json
from typing import Optional, Mapping
from types import MappingProxyType
from mashumaro import DataClassJSONMixin
from mashumaro.serializer.json import Encoder,EncodedData,DEFAULT_DICT_PARAMS,T

@dataclass
class MyClass(DataClassJSONMixin):
    name: str
    soul: str = None

    def to_json(
        self: T,
        encoder: Optional[Encoder] = json.dumps,
        dict_params: Optional[Mapping] = MappingProxyType({}),
        **encoder_kwargs) -> EncodedData:

        dct = self.to_dict(**dict(DEFAULT_DICT_PARAMS, **dict_params))

        for key,f in self.__class__.__dataclass_fields__.items():
            if dct[key] == f.default:
                dct.pop(key)

        return encoder(
            dct,
            **encoder_kwargs
        )

c=MyClass('itseme')
print(to_json())

from mashumaro.

Fatal1ty avatar Fatal1ty commented on May 22, 2024

Hi @atteneder

Your solution seems to work with nested classes as well.

@dataclass
class MyClassChild(MyClass, DataClassJSONMixin):
    another: str = ''

c = MyClassChild('itseme')
print(c.to_json())  # {"name": "itseme"}


@dataclass
class Parent(DataClassJSONMixin):
    a: str
    b: str = None

    def to_json(
        self: T,
        encoder: Optional[Encoder] = json.dumps,
        dict_params: Optional[Mapping] = MappingProxyType({}),
        **encoder_kwargs) -> EncodedData:

        dct = self.to_dict(**dict(DEFAULT_DICT_PARAMS, **dict_params))

        for key,f in self.__class__.__dataclass_fields__.items():
            if dct[key] == f.default:
                dct.pop(key)

        return encoder(
            dct,
            **encoder_kwargs
        )

@dataclass
class Child(Parent, DataClassJSONMixin):
    c: str = None

c = Child('a')
print(c.to_json())  # {"a": "a"}

Could you write an example of what doesn't work?

from mashumaro.

atteneder avatar atteneder commented on May 22, 2024

Sure!

What I meant was nested dataclasses:

import json
from dataclasses import dataclass
from typing import Optional, Mapping
from types import MappingProxyType
from mashumaro import DataClassJSONMixin
from mashumaro.serializer.json import Encoder,EncodedData,DEFAULT_DICT_PARAMS,T

@dataclass
class SkipperBase(DataClassJSONMixin):
    def to_json(
        self: T,
        encoder: Optional[Encoder] = json.dumps,
        dict_params: Optional[Mapping] = MappingProxyType({}),
        **encoder_kwargs) -> EncodedData:

        dct = self.to_dict(**dict(DEFAULT_DICT_PARAMS, **dict_params))

        for key,f in self.__class__.__dataclass_fields__.items():
            if dct[key] == f.default:
                dct.pop(key)

        return encoder(
            dct,
            **encoder_kwargs
        )

@dataclass
class MyClass(SkipperBase):
    name: str
    soul: str = None

@dataclass
class MyParentClass(SkipperBase):
    child: MyClass = None

p=MyParentClass()
p.child = MyClass('itseme')
print(p.to_json())

output: {"child": {"name": "itseme", "soul": null}}
desired output: {"child": {"name": "itseme"}}

That's because the child is converted to a dict (with all default params as well) and serialized to JSON within the parent's to_json.

I guess I could override the to_dict (so that it skips default members), but that's an odd default behaviour. Ideally to_dict has a parameter for skipping default values that gets propagated to nested members.

What do you think?

from mashumaro.

Fatal1ty avatar Fatal1ty commented on May 22, 2024

I think the additional parameter in to_dict will solve the problem perfectly. But we need to check how much it will affect performance. Unfortunately, I don’t have enough time the next few days. It would be great if you made changes and opened a pull request. But if you don’t, I will try to find time to check it out.

from mashumaro.

rominf avatar rominf commented on May 22, 2024

Any updates on this? I need this too.

from mashumaro.

atteneder avatar atteneder commented on May 22, 2024

Sorry, seems I won't have time to tinker with this.
I've been using dataclasses-json as an alternative lately. Maybe it works for this case as well.

from mashumaro.

Fatal1ty avatar Fatal1ty commented on May 22, 2024

It's possible to skip None values with the optional omit_none code generation flag:

from dataclasses import dataclass

from mashumaro import DataClassJSONMixin
from mashumaro.config import TO_DICT_ADD_OMIT_NONE_FLAG

@dataclass
class MyClass(DataClassJSONMixin):
    name: str = None
    soul: str = None

    class Config:
        code_generation_options = [TO_DICT_ADD_OMIT_NONE_FLAG]

c = MyClass()
c.name = 'itseme'

print(c.to_json(dict_params=dict(omit_none=True)))  # {"name": "itseme"}

At the moment this flag exists in the master branch but it will be released in the next version.

from mashumaro.

atteneder avatar atteneder commented on May 22, 2024

Thank you very much for offering a solution!

To me this is satisfactory. It seems to not work for non-None default values, however.

@Fatal1ty Feel free to close the issue or keep it open for said shortcoming.

Again, thanks for this library!

from mashumaro.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.