Skip to content

Instantly share code, notes, and snippets.

@quinnj
Created Feb 25, 2021
Embed
What would you like to do?
function generate(json)
x = JSON3.read(json)
structs = []
generate!(structs, x)
return generatejulia(structs)
end
struct Struct
name::String
names::Vector{Symbol}
types::Vector{Any}
end
generate!(structs, x) = generate!(structs, "Root", x)
function generate!(structs, name, x::JSON3.Object)
isempty(x) && return Any
names = Symbol[]
types = []
for (k, v) in x
push!(names, k)
push!(types, generate!(structs, titlecase(String(k)), v))
end
push!(structs, Struct(name, names, types))
return name
end
generate!(structs, name, x::JSON3.Array{T}) where {T} = "Vector{$(isempty(x) ? generate!(structs, string(name, "s"), T) : generate!(structs, string(name, "s"), x[1]))}"
generate!(structs, k, x::T) where {T} = T
generate!(structs, k, ::Type{T}) where {T} = T
generate!(structs, k, ::Type{JSON3.Object}) = Any
function generatejulia(structs)
io = IOBuffer()
Base.write(io, """
using StructTypes, JSON3
""")
for x in structs
fields = join(["$name::$type" for (name, type) in zip(x.names, x.types)], "\n")
Base.write(io, """
mutable struct $(x.name)
$fields
$(x.name)() = new()
end
StructTypes.StructType(::Type{$(x.name)}) = StructTypes.Mutable()
""")
end
return String(take!(io))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment