1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
|
Examples
========
Simple
~~~~~~
The following example has been tested on **Python 3.9+**.
.. code:: python3
# Note: in Python 3.10+, this import can be removed
from __future__ import annotations
from dataclasses import dataclass, field
from dataclass_wizard import JSONWizard
@dataclass
class MyClass(JSONWizard):
my_str: str | None
is_active_tuple: tuple[bool, ...]
list_of_int: list[int] = field(default_factory=list)
string = """
{
"my_str": 20,
"ListOfInt": ["1", "2", 3],
"isActiveTuple": ["true", "false", 1, false]
}
"""
# De-serialize the JSON string into a `MyClass` object.
c = MyClass.from_json(string)
print(repr(c))
# prints:
# MyClass(my_str='20', is_active_tuple=(True, False, True, False), list_of_int=[1, 2, 3])
print(c.to_json())
# prints:
# {"myStr": "20", "isActiveTuple": [true, false, true, false], "listOfInt": [1, 2, 3]}
# True
assert c == c.from_dict(c.to_dict())
Using Typing Imports (Deprecated)
---------------------------------
This approach is supported in **Python 3.6**. Usage is the same as above.
.. code:: python3
from dataclasses import dataclass, field
from typing import Optional, List, Tuple
from dataclass_wizard import JSONWizard
@dataclass
class MyClass(JSONWizard):
my_str: Optional[str]
is_active_tuple: Tuple[bool, ...]
list_of_int: List[int] = field(default_factory=list)
A (More) Complete Example
~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: python3
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional, Literal, Union, Any, NamedTuple
from dataclass_wizard import JSONSerializable
@dataclass
class MyTestClass(JSONSerializable):
my_ledger: dict[str, Any]
the_answer_to_life: Optional[int]
people: list['Person']
is_enabled: bool = True
@dataclass
class Person:
name: 'Name'
age: int
birthdate: datetime
gender: Literal['M', 'F', 'N/A']
occupation: Union[str, list[str]]
hobbies: defaultdict[str, list[str]] = field(
default_factory=lambda: defaultdict(list))
class Name(NamedTuple):
"""A person's name"""
first: str
last: str
salutation: Optional[Literal['Mr.', 'Mrs.', 'Ms.', 'Dr.']] = 'Mr.'
data = {
'myLedger': {
'Day 1': 'some details',
'Day 17': ['a', 'sample', 'list']
},
'theAnswerTOLife': '42',
'People': [
{
'name': ('Roberto', 'Fuirron'),
'age': 21,
'birthdate': '1950-02-28T17:35:20Z',
'gender': 'M',
'occupation': ['sailor', 'fisher'],
'Hobbies': {'M-F': ('chess', 123, 'reading'), 'Sat-Sun': ['parasailing']}
},
{
'name': ('Janice', 'Darr', 'Dr.'),
'age': 45,
'birthdate': '1971-11-05 05:10:59',
'gender': 'F',
'occupation': 'Dentist'
}
]
}
c = MyTestClass.from_dict(data)
print(repr(c))
# prints the following result on a single line:
# MyTestClass(
# my_ledger={'Day 1': 'some details', 'Day 17': ['a', 'sample', 'list']},
# the_answer_to_life=42,
# people=[
# Person(
# name=Name(first='Roberto', last='Fuirron', salutation='Mr.'),
# age=21, birthdate=datetime.datetime(1950, 2, 28, 17, 35, 20, tzinfo=datetime.timezone.utc),
# gender='M', occupation=['sailor', 'fisher'],
# hobbies=defaultdict(<class 'list'>, {'M-F': ['chess', '123', 'reading'], 'Sat-Sun': ['parasailing']})
# ),
# Person(
# name=Name(first='Janice', last='Darr', salutation='Dr.'),
# age=45, birthdate=datetime.datetime(1971, 11, 5, 5, 10, 59),
# gender='F', occupation='Dentist',
# hobbies=defaultdict(<class 'list'>, {})
# )
# ], is_enabled=True)
# calling `print` on the object invokes the `__str__` method, which will
# pretty-print the JSON representation of the object by default. You can
# also call the `to_json` method to print the JSON string on a single line.
print(c)
# prints:
# {
# "myLedger": {
# "Day 1": "some details",
# "Day 17": [
# "a",
# "sample",
# "list"
# ]
# },
# "theAnswerToLife": 42,
# "people": [
# {
# "name": [
# "Roberto",
# "Fuirron",
# "Mr."
# ],
# "age": 21,
# "birthdate": "1950-02-28T17:35:20Z",
# "gender": "M",
# "occupation": [
# "sailor",
# "fisher"
# ],
# "hobbies": {
# "M-F": [
# "chess",
# "123",
# "reading"
# ],
# "Sat-Sun": [
# "parasailing"
# ]
# }
# },
# {
# "name": [
# "Janice",
# "Darr",
# "Dr."
# ],
# "age": 45,
# "birthdate": "1971-11-05T05:10:59",
# "gender": "F",
# "occupation": "Dentist",
# "hobbies": {}
# }
# ],
# "isEnabled": true
# }
|