0

Just found this very neat way in Go to define the correlating json key for a class attribute, where the former is the class attribute definition and the latter what key it translates to in a json.

This approach allows to auto-magically serialize a class to a given json-structure (e.g. when you're dealing with many different REST APIs that expect different payloads) but also allows translating a json payload to a class instance.

Any way of achieving something similar with Python? I so far always tried to map my attribute names to the json structure, but it becomes an impractical mess when the API e.g. deals with camelCase or some abbreviations instead.

type EmailpkiSmime struct {
    Locked     string `json:"_locked"`
    ObjectType string `json:"_type"`
    Reference  string `json:"_ref"`
    Cert       string `json:"cert"`
    Comment    string `json:"comment"`
    Dn         string `json:"dn"`
    // Domaincert default value is false
    Domaincert  bool     `json:"domaincert"`
    Emails      []string `json:"emails"`
    Expires     string   `json:"expires"`
    Fingerprint string   `json:"fingerprint"`
    // Key default value is ""
    Key  string `json:"key"`
    Name string `json:"name"`
    // Realname default value is ""
    Realname string `json:"realname"`
    // Trust default value is false
    Trust bool `json:"trust"`
}
schlumpfpirat
  • 195
  • 2
  • 12
  • Dataclasses in python might be the thing you are looking for: https://docs.python.org/3/library/dataclasses.html – dben Aug 22 '22 at 14:06
  • marshmallow + marshmallow-dataclasses can do this for you, see the duplicate. – Martijn Pieters Aug 22 '22 at 14:08
  • Use either a library like dataclass-wizard which supports [custom key mappings](https://dataclass-wizard.readthedocs.io/en/latest/common_use_cases/custom_key_mappings.html) and also adds auto type conversion, or also check out [a gist](https://gist.github.com/rnag/ddd678b42af0ed97193c8b763d216d58) I added which allows you to set up field aliases for a simple dataclass, and then just initialize it from a dictionary object, `**kwargs` style. – rv.kvetch Aug 22 '22 at 16:13

0 Answers0