https://github.com/lyang/pynamodb-encoder
PynamoDB Model object encoder/decoder to/from dict.
https://github.com/lyang/pynamodb-encoder
dynamodb encoder-decoder json polymorphic pynamodb python
Last synced: 4 days ago
JSON representation
PynamoDB Model object encoder/decoder to/from dict.
- Host: GitHub
- URL: https://github.com/lyang/pynamodb-encoder
- Owner: lyang
- License: mit
- Created: 2021-11-27T04:22:45.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2026-01-29T05:21:47.000Z (26 days ago)
- Last Synced: 2026-01-29T07:33:45.760Z (26 days ago)
- Topics: dynamodb, encoder-decoder, json, polymorphic, pynamodb, python
- Language: Python
- Homepage:
- Size: 531 KB
- Stars: 6
- Watchers: 1
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# pynamodb-encoder
  [](https://codecov.io/gh/lyang/pynamodb-encoder) [](https://codeclimate.com/github/lyang/pynamodb-encoder/maintainability) [](https://badge.fury.io/py/pynamodb-encoder)
[](https://pypi.python.org/pypi/pynamodb-encoder/)
## Introduction
`pynamodb-encoder` provides helper classes that can convert [PynamoDB](https://github.com/pynamodb/PynamoDB) `Model` objects into `JSON` serializable `dict`. It can also decode such `dict` back into those `Model` objects. [Polymorphic](https://pynamodb.readthedocs.io/en/latest/polymorphism.html) models and attributes are also supported.
## Examples
```python
def test_encode_complex_model(encoder: Encoder):
class Pet(DynamicMapAttribute):
cls = DiscriminatorAttribute()
name = UnicodeAttribute()
class Cat(Pet, discriminator="Cat"):
pass
class Dog(Pet, discriminator="Dog"):
pass
class Human(Model):
name = UnicodeAttribute()
pets = ListAttribute(of=Pet)
jon = Human(name="Jon", pets=[Cat(name="Garfield", age=43), Dog(name="Odie")])
assert encoder.encode(jon) == {
"name": "Jon",
"pets": [{"cls": "Cat", "name": "Garfield", "age": 43}, {"cls": "Dog", "name": "Odie"}],
}
def test_decode_complex_model(decoder: Decoder):
class Pet(DynamicMapAttribute):
cls = DiscriminatorAttribute()
class Cat(Pet, discriminator="Cat"):
name = UnicodeAttribute()
class Dog(Pet, discriminator="Dog"):
breed = UnicodeAttribute()
class Human(Model):
name = UnicodeAttribute()
age = NumberAttribute()
pets = ListAttribute(of=Pet)
jon = decoder.decode(
Human,
{
"name": "Jon",
"age": 70,
"pets": [{"cls": "Cat", "name": "Garfield"}, {"cls": "Dog", "breed": "Terrier"}],
},
)
assert jon.name == "Jon"
assert jon.age == 70
assert isinstance(jon.pets, list)
assert len(jon.pets) == 2
assert isinstance(jon.pets[0], Cat)
assert jon.pets[0].name == "Garfield"
assert isinstance(jon.pets[1], Dog)
assert jon.pets[1].breed == "Terrier"
```
More examples can be found in [encoder_test.py](tests/encoder_test.py) and [decoder_test.py](tests/decoder_test.py)