Skip to content

Serialization using parsled#

Basic usage#

We have 2 main ways to serialize Python objects.

  1. Call to_sled().
  2. Instantiate a SledSerializer and call its to_sled() method.

Both have the same configuration options and defaults. For details, refer to the SledSerializer documentation.

Approach #1 simply does approach #2 under the hood. Approach #2 may be useful if you want to set a configuration once and reuse that for serialization multiple times.

Python
data = {}
other_data = {}

# Approach #1
sled_output = parsled.to_sled(data)

# Approach #2
sled_serializer = parsled.SledSerializer()
sled_output = sled_serializer.to_sled(data)
other_sled_output = sled_serializer.to_sled(other_data)

Data types#

By default, instances of the following Python data types (on the left) will be serialized to the corresponding Sled data type (on the right).

  • None: nil
  • bool: boolean
  • bytes: hex
  • int: integer
  • float: float
  • str: identity, quote, or concat
  • Mapping[str, Entity]: smap
  • Mapping[int, Entity]: imap
  • Iterable that is not a Mapping: list
  • dataclass: smap

For an object to be serialized as a standalone Sled document, it should be a Mapping[str, Entity] or dataclass instance, since the top level of a Sled document is always a smap.

A dataclass instance is implicitly converted into a Mapping by calling dataclasses.fields() (unless the original instance is itself also a Mapping, in which case that takes precedence).

Mini serialization#

Minified serialization produces a more compact but less human-friendly output.

The interface is analogous to to_sled() and SledSerializer respectively.

  1. Call to_sled_mini().
  2. Instantiate a SledSerializerMini and call its to_sled() method.

Both have the same configuration options and defaults. Refer to their documentation for details.

Approach #1 simply does approach #2 under the hood. Approach #2 may be useful if you want to set a configuration once and reuse that for serialization multiple times.

Python
data = {}
other_data = {}

# Approach #1
sled_output = parsled.to_sled_mini(data)

# Approach #2
serializer = parsled.SledSerializerMini()
sled_output = serializer.to_sled(data)
other_sled_output = serializer.to_sled(other_data)