How does one alias JSON in a Julia struct like in Go?

Viewed 248

In GoLang, one can alias JSON for serializing and serializing/de-serializing:

 type Response struct {
      TaskID     string     `json:"task_id"`
 ...
 }
 ...
 func Run(task structs.Task) {
      msg := structs.Response{}
      msg.TaskID = task.TaskID
      resp, _ := json.Marshal(msg)
 ...
 }

json:"task_id" is the alias for the struct field TaskID with the string type in the Response struct of the GoLang example above. This alias can be used to serialize the struct data into JSON as exemplified in json.Marshal(msg)

How can one accomplish this in Julia?

1 Answers

You can use StructTypes.names function:

using JSON3
using StructTypes

Base.@kwdef mutable struct Foo
    task_id::Int = 0
    bar::String  = ""
end
StructTypes.StructType(::Type{Foo}) = StructTypes.Mutable()
StructTypes.names(::Type{Foo}) = ((:task_id, :TASKID), )

With these definitions serialization and deserialization looks like this

julia> f1 = JSON3.read("{\"TASKID\": 1, \"bar\": \"hello\"}", Foo)
Foo(1, "hello")

julia> JSON3.write(f1)
"{\"TASKID\":1,\"bar\":\"hello\"}"
Related