[ANN] TypeAgnosticSerialisation.jl: safely serialise and deserialise Julia types into various schema

TypeAgnosticSerialisation.jl

Claude and I wrote a little package because I needed a way to port my structs through sessions. This was the result.

It serialises and deserialises to and from JSON, YAML, TOML and MessagePack. Types that are unsafe need to be declared as opaque so the serialising/deserialising functions don’t throw. If they cannot be reconstructed they are not. You also need to provide a list of modules that define the types.

There are direct reconstructions that go through new (they skip any validation in the positional constructors) and indirect reconstructions which go through the type’s constructor so they can be validated.

julia> using TypeAgnosticSerialisation

julia> import JSON

julia> module Shapes
           export AbstractShape, Circle, Rect, Square, Color, red, green, blue, Scene, Handle, Doc
           abstract type AbstractShape end
           struct Circle{T} <: AbstractShape
               r::T
               function Circle{T}(r::T) where {T}
                   r > 0 || error("Circle: radius must be positive")
                   return new{T}(r)
               end
           end
           Circle(r::T) where {T} = Circle{T}(r)
           struct Rect{T} <: AbstractShape
               w::T
               h::T
           end
           struct Square <: AbstractShape end
           @enum Color red green blue
           struct Scene
               shapes::Vector{AbstractShape}
               bg::Color
           end
           struct Handle
               ptr::Ptr{Cvoid}
               Handle() = new(C_NULL)
           end
           struct Doc
               title::String
               handle::Handle
           end
       end;

julia> using .Shapes

julia> scene = Scene(AbstractShape[Circle(1.5), Rect(3, 4), Square()], green);

julia> json = to_json(scene; modules = (Shapes,));

julia> back = from_json(json; modules = (Shapes,));

julia> back.shapes[1] isa Circle{Float64}
true

julia> back.shapes[2] isa Rect{Int}
true

julia> (back.shapes[1].r, back.shapes[2].w, back.shapes[2].h)
(1.5, 3, 4)

julia> back.bg === green
true

The schema contains all the metadata as well as the package version of the struct’s owner module so you can match a struct’s version.