You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+29Lines changed: 29 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -24,6 +24,7 @@ python-benedict is a dict subclass with **keylist/keypath/keyattr** support, **I
24
24
-**Keypath** support using **keypath-separator***(dot syntax by default)*.
25
25
- Keypath **list-index** support *(also negative)* using the standard `[n]` suffix.
26
26
- Normalized **I/O operations** with most common formats: `base64`, `cli`, `csv`, `html`, `ini`, `json`, `pickle`, `plist`, `query-string`, `toml`, `xls`, `xml`, `yaml`.
27
+
-`NEW` Optional **Pydantic v2 schema** validation and type coercion on all `from_*` / `to_*` I/O methods via the `schema` kwarg *(requires `python-benedict[schema]`).*
- Many **utility** and **parse methods** to retrieve data as needed *(check the [API](#api) section)*.
29
30
- Well **tested**. ;)
@@ -68,6 +69,7 @@ Here the hierarchy of possible installation targets available when running `pip
68
69
- `[yaml]`
69
70
-`[parse]`
70
71
-`[s3]`
72
+
-`[schema]`
71
73
72
74
## Usage
73
75
@@ -614,6 +616,29 @@ d.unique()
614
616
615
617
These methods are available for input/output operations.
616
618
619
+
All `from_*` and `to_*` methods accept an optional `schema` keyword argument. When a [Pydantic v2](https://docs.pydantic.dev/) model class is passed, the data is validated and type-coerced through the model before being returned (on decode) or serialized (on encode). This requires the `python-benedict[schema]` extra.
620
+
621
+
```
622
+
pip install "python-benedict[schema]"
623
+
```
624
+
625
+
```python
626
+
from benedict import benedict
627
+
from pydantic import BaseModel
628
+
629
+
classUser(BaseModel):
630
+
name: str
631
+
age: int
632
+
633
+
# validate and coerce types on decode
634
+
d = benedict.from_json('{"name": "Alice", "age": "30"}', schema=User)
635
+
assert d["age"] ==30# coerced from str to int
636
+
637
+
# validate and coerce types on encode
638
+
d = benedict({"name": "Bob", "age": "25"})
639
+
s = d.to_json(schema=User) # age is coerced to int before serialization
640
+
```
641
+
617
642
#### `from_base64`
618
643
619
644
```python
@@ -666,6 +691,7 @@ d = benedict.from_html(s, **kwargs)
666
691
# Accept as first argument: url, filepath or data-string.
667
692
# It's possible to pass decoder specific options using kwargs:
0 commit comments