Utilities
Flatten
Serde.to_flatten — Function
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 nestedAbstractDictor 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.
Errors
Serde.SerdeError — Type
SerdeError <: ExceptionAbstract 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()
endSee also: ParseError, DeserError, MissingFieldError, TypeMismatchError, ValidationError.
Serde.ParseError — Type
ParseError <: SerdeErrorThrown 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 syntaxSee also: SerdeError, DeserError.
Serde.DeserError — Type
DeserError <: SerdeErrorAbstract base for all field-level deserialization errors. Catch DeserError to handle any structural mismatch between the parsed data and the target type.
Concrete subtypes:
MissingFieldError— a required field is absent.TypeMismatchError— a field value has an incompatible type.ValidationError— a field value fails a custom validation check.
See also: SerdeError.
Serde.MissingFieldError — Type
MissingFieldError <: DeserErrorThrown 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.
Serde.TypeMismatchError — Type
TypeMismatchError <: DeserErrorThrown 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: portSee also: DeserError.
Serde.ValidationError — Type
ValidationError <: DeserErrorThrown 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-negativeSee also: Serde.deser_validate, DeserError.
Tagged unions
Serde.register_tagged_subtype — Function
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 selectssubtype.subtype::Type: the concrete struct type to construct whentag_valis 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.