Add field to standard JSON serialization


I basically want to achieve what is explained in this post:

When calling JSON.json on an object, add a Pair type => string(typeof(t)) for child types of a certain abstract type. A cpuple restrictions:

  • I need to use the default JSON library.
  • I don’t want to specify the JSON.lower method manually, just to expand on the standard serialization.

I have read the JSON.jl documentation, but it’s unclear to me on how I can achieve this.

Any ideas? Thank you in advance.

This seems like the simplest solution, not sure if it has downsides:

function JSON.lower(e::MyAbstractType)
    result = Dict()
    for field in fieldnames(typeof(e))
        push!(result, field => getfield(e, field))
    push!(result, :type => string(typeof(e)))