Skip to main content

Covert msgspec object to dict

· 2 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

To convert a msgspec object to a dict, you can use the msgspec.structs.asdict() function. This function recursively converts a msgspec.Struct instance into a dictionary, including any nested Struct objects.

Here's a simple example:

import msgspec

class User(msgspec.Struct):
name: str
age: int

class Team(msgspec.Struct):
id: int
members: list[User]

# Create a msgspec object
team = Team(id=1, members=[User(name="Alice", age=30), User(name="Bob", age=25)])

# Convert the msgspec object to a dictionary
team_dict = msgspec.structs.asdict(team)

print(team_dict)
# Output: {'id': 1, 'members': [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]}

Alternatively, you can use msgspec.json.encode() and json.loads() for a round-trip conversion, which is useful if you also need to handle JSON serialization.

import msgspec
import json

class User(msgspec.Struct):
name: str
age: int

# Create a msgspec object
user = User(name="Charlie", age=42)

# Encode the msgspec object to JSON bytes
user_json_bytes = msgspec.json.encode(user)

# Decode the JSON bytes to a Python dictionary
user_dict = json.loads(user_json_bytes)

print(user_dict)
# Output: {'name': 'Charlie', 'age': 42}