Created
February 25, 2021 16:45
-
-
Save quinnj/ece123e1d291b639fc0121178f2c353a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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