Utilities

Flatten

Serde.to_flattenFunction
Serde.to_flatten(data; delimiter = "_") -> Dict{String, Any}

Flattens a nested dictionary or struct into a single-level Dict{String,Any}.

Keys at each nesting level are concatenated with delimiter. Nested dicts and nested structs (types whose ClassType is StructClass) are both expanded recursively; scalar values are left as-is.

Arguments

  • data: a nested AbstractDict or any struct value.

Keyword arguments

  • delimiter::AbstractString = "_": separator inserted between parent and child key names.
  • dict_type::Type{<:AbstractDict} = Dict{String,Any}: the concrete dict type to use for the result.

Returns

A flat dict_type with all keys joined by delimiter.

Examples

julia> nested = Dict("a" => 1, "b" => Dict("c" => 2, "d" => Dict("e" => 3)));

julia> Serde.to_flatten(nested)
Dict{String, Any} with 3 entries:
  "a"     => 1
  "b_c"   => 2
  "b_d_e" => 3

julia> struct Address; city::String; zip::String; end

julia> struct Person; name::String; address::Address; end

julia> Serde.to_flatten(Person("Alice", Address("NY", "10001")))
Dict{String, Any} with 3 entries:
  "name"         => "Alice"
  "address_city" => "NY"
  "address_zip"  => "10001"

See also: Serde.ser_pairs.

source

Errors

Serde.SerdeErrorType
SerdeError <: Exception

Abstract base type for all errors thrown by Serde. There are two branches:

  • ParseError — the raw input is malformed (unparseable format bytes/text).
  • DeserError — the data parsed successfully but cannot be mapped to the target type.

Catch SerdeError to handle both categories uniformly:

result = try
    from_json(MyType, json_string)
catch e
    e isa SerdeError ? handle_error(e) : rethrow()
end

See also: ParseError, DeserError, MissingFieldError, TypeMismatchError, ValidationError.

source
Serde.ParseErrorType
ParseError <: SerdeError

Thrown when the raw input cannot be parsed as the expected format (malformed JSON, YAML, etc.).

Fields

  • format::String: the format name ("JSON", "YAML", "TOML", "CSV", "XML", "Query", "MsgPack", "BSON").
  • message::String: human-readable description of the failure.
  • cause::Exception: the underlying exception from the format parser.

Examples

julia> try
           from_json(Int, "not json")
       catch e
           e isa ParseError && println(e.format, ": ", e.message)
       end
JSON: invalid JSON syntax

See also: SerdeError, DeserError.

source
Serde.DeserErrorType
DeserError <: SerdeError

Abstract base for all field-level deserialization errors. Catch DeserError to handle any structural mismatch between the parsed data and the target type.

Concrete subtypes:

See also: SerdeError.

source
Serde.MissingFieldErrorType
MissingFieldError <: DeserError

Thrown when a required field is absent from the input during deserialization. A field is required unless Serde.has_default returns true for it or its type is nullable (Union{Nothing,T}, Union{Missing,T}).

Fields

  • type::Type: the target struct type being constructed.
  • field::Symbol: the name of the missing field.

Examples

julia> struct Config
           host::String
           port::Int
       end

julia> try
           from_json(Config, "{"host":"localhost"}")
       catch e
           println(e)
       end
MissingFieldError: type 'Config' requires field 'port'

See also: Serde.has_default, Serde.deser_default.

source
Serde.TypeMismatchErrorType
TypeMismatchError <: DeserError

Thrown when the value found in the input cannot be converted to the expected field type.

Fields

  • type::Type: the struct type being constructed.
  • field::Symbol: the field where the mismatch occurred.
  • expected::Type: the Julia type declared for this field.
  • got::Type: the actual type of the value found in the input.
  • value::Any: the offending value.

Examples

julia> struct Cfg; port::Int; end

julia> try
           from_json(Cfg, "{"port":"not_a_number"}")
       catch e
           e isa TypeMismatchError && println("field: ", e.field)
       end
field: port

See also: DeserError.

source
Serde.ValidationErrorType
ValidationError <: DeserError

Thrown when a deserialized field value fails a custom validation rule defined via Serde.deser_validate.

Fields

  • type::Type: the target struct type.
  • field::Symbol: the field that failed validation.
  • value::Any: the value that was rejected.
  • message::String: human-readable description of the failure.

Examples

julia> struct Age
           value::Int
       end

julia> function Serde.deser_validate(::Type{Age}, ::Val{:value}, v::Int)
           v >= 0 || throw(ValidationError(Age, :value, v, "age must be non-negative"))
       end

julia> try
           Serde.deser(Age, Dict("value" => -1))
       catch e
           println(e)
       end
ValidationError: field 'value' of Age (value: -1): age must be non-negative

See also: Serde.deser_validate, DeserError.

source

Tagged unions

Serde.register_tagged_subtypeFunction
register_tagged_subtype(parent::Type, tag_val::String, subtype::Type)

Register subtype as a concrete variant of the tagged-union abstract type parent, identified by the discriminator value tag_val.

The parent type must have Serde.ClassType(::Type{<:parent}) = Serde.TaggedClass() and Serde.tag_key(::Type{<:parent}) defined before calling this function.

Arguments

  • parent::Type: the abstract tagged-union type.
  • tag_val::String: the discriminator string that selects subtype.
  • subtype::Type: the concrete struct type to construct when tag_val is found.

Examples

abstract type Event end
Serde.ClassType(::Type{<:Event}) = Serde.TaggedClass()
Serde.tag_key(::Type{<:Event}) = "kind"

struct LoginEvent <: Event
    user_id::Int
end

struct LogoutEvent <: Event
    user_id::Int
    session_ms::Int
end

register_tagged_subtype(Event, "login",  LoginEvent)
register_tagged_subtype(Event, "logout", LogoutEvent)

# Now from_json dispatches on "kind":
json = """{"kind":"login","user_id":42}"""
from_json(Event, json)  # → LoginEvent(42)

See also: Serde.tag_key, Serde.tag_subtypes, TaggedClass.

source