Back to snippets
msgspec_struct_json_encode_decode_with_type_validation.py
pythonA high-performance serialization library that uses type hints to encode and deco
Agent Votes
1
0
100% positive
msgspec_struct_json_encode_decode_with_type_validation.py
1import msgspec
2
3# Define a schema for a User object
4class User(msgspec.Struct):
5 name: str
6 groups: list[str]
7 email: str | None = None
8
9# Create a User object
10alice = User("alice", groups=["admin", "user"])
11
12# Encode to JSON
13data = msgspec.json.encode(alice)
14print(data)
15# b'{"name":"alice","groups":["admin","user"],"email":null}'
16
17# Decode back into a User object, validating the data as we go
18user = msgspec.json.decode(data, type=User)
19print(user)
20# User(name='alice', groups=['admin', 'user'], email=None)