Comments (8)
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.
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.
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.
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.
Any updates on this? I need this too.
from mashumaro.
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.
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.
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)
- Can immutable dataclasses be hashed as dictionary keys? HOT 4
- Add an option to omit values equal to defaults on serialization
- Add an option to avoid collection data types copying
- Add support for LiteralString
- Generic dataclasses with Hashable typevar bound do not work HOT 3
- Query string support HOT 5
- Benchmark is not working in master branch HOT 2
- omit_default=True evaluates default_factory value at declaration time which can cause a circular reference HOT 3
- Multiple aliases for field HOT 6
- "`dict[str, T]` as a field type is not supported" HOT 2
- InitVar with no default value HOT 6
- The types defined inside the function result in syntactically invalid generated code
- Allow for more complex logic for subclass Discrimnator field matching HOT 3
- TypedDicts not working with `from __future__ import annotations` HOT 2
- omit_default breaks IntFlag serialization HOT 1
- Using Union with int/float casts to whichever appears first HOT 3
- Not parsing Generics correctly HOT 2
- Unserializable field in 3.12 if defined as a Generic TypeVar with mixin bounds HOT 6
- Allow propagation of class based discriminator settings to subclasses HOT 3
- Reject extra keys on deserialization HOT 7
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mashumaro.