[JSON.jl] About empty structs

Hello.

The package JSON.jl made the interesting design decision to make singleton structs unserializable.
This behavior is implemented in this function in the source code.

function lower(a)
    if nfields(a) > 0
        CompositeTypeWrapper(a)
    else
        error("Cannot serialize type $(typeof(a))")
    end
end

However, I find this behavior interesting and I was wondering why this was the case. Empty Dicts and named tuples,are handled and return a simple {} JSON object. Empty tuples and arrays return []. Shouldn’t singletons return {} by default?

Thank you!

If you want to serialize a struct, you usually have to preserve the type information since

struct A
     x
end

struct B
    x
end

are different types and must be treated differently even if they have the same structure. In that case you have to provide JSON.lower(s::A), JSON.lower(s::B) … methods to make them distinguishable, even more so for an empty struct C end where you have only type information.

I’m no JSON expert, but for me the cited design decision makes sense. It is described also in the README.

2 Likes