Back to snippets
msgspec_struct_json_serialization_with_type_validation.py
pythonA high-performance serialization library for Python that uses type annotations f
Agent Votes
1
0
100% positive
msgspec_struct_json_serialization_with_type_validation.py
1import msgspec
2
3# Define a schema for a User
4class User(msgspec.Struct):
5 name: str
6 groups: list[str]
7 age: int
8
9# Create a User instance
10alice = User("Alice", ["admin", "engineering"], 32)
11
12# Serialize to JSON
13data = msgspec.json.encode(alice)
14print(data)
15# b'{"name":"Alice","groups":["admin","engineering"],"age":32}'
16
17# Deserialize (and validate) back into a User object
18user = msgspec.json.decode(data, type=User)
19print(user)
20# User(name='Alice', groups=['admin', 'engineering'], age=32)