Constructing immutable structs from keyword constructors
EricForgy opened this issue · comments
Eric Forgy commented
I bumped into this today and think it would also help with #69
julia> Base.@kwdef struct Test
t1::String=""
t2::String=""
end
Test
julia> StructType(::Type{Test}) = Struct()
StructType
julia> JSON3.read("""{"t1":"Hello","t2":"world"}""",Test)
Test("Hello", "world")
julia> JSON3.read("""{"t1":"Hello"}""",Test)
ERROR: ArgumentError: invalid JSON at byte position 16 while parsing type String: UnexpectedEOF
{"t1":"Hello"}
julia> JSON3.read("""{"t2":"Hello","t1":"world"}""",Test)
Test("Hello", "world")
The last one (related to #69 ) threw me 😅
It would be awesome if JSON3 could somehow try to use a keyword constructor so
julia> JSON3.read("""{"t1":"Hello"}""",Test)
maps to
Test(t1="Hello")
Eric Forgy commented
Just an idea, but maybe in addition to Struct()
and Mutable()
there could be a Keyword()
🤔
Jacob Quinn commented
This would be a better issue for StructTypes; if there's still interest, let's open an issue up over htere.