JSON3.jl icon indicating copy to clipboard operation
JSON3.jl copied to clipboard

Creating structs which use default field values

Open alhirzel opened this issue 3 years ago • 3 comments

After #136, is there a good way to use defaults for structs created from read? For instance, the following currently breaks because of the type of field foo.

using JSON3, Parameters, StructTypes

@with_kw struct S
    foo::String = "bar"
    num::Int64
end

StructTypes.StructType(::Type{S}) = StructTypes.Struct()

@show JSON3.read("""{"num": 42}""", S) # error

The error is as follows:

ERROR: LoadError: MethodError: Cannot `convert` an object of type Nothing to an object of type String
Closest candidates are:
  convert(::Type{String}, ::String) at essentials.jl:210
  convert(::Type{T}, ::T) where T<:AbstractString at strings/basic.jl:231
  convert(::Type{T}, ::AbstractString) where T<:AbstractString at strings/basic.jl:232
  ...
Stacktrace:
 [1] S(foo::Nothing, num::Int64)
   @ Main ~/.julia/packages/Parameters/cGriM/src/Parameters.jl:480
 [2] construct
   @ ~/.julia/packages/StructTypes/3yLxJ/src/StructTypes.jl:869 [inlined]
 [3] #read#43
   @ ~/.julia/packages/JSON3/czMzK/src/structs.jl:578 [inlined]
 [4] read
   @ ~/.julia/packages/JSON3/czMzK/src/structs.jl:500 [inlined]
 [5] read(str::String, ::Type{S}; kw::Base.Iterators.Pairs{Union{}, Union{}, Tuple{}, NamedTuple{(), Tuple{}}})
   @ JSON3 ~/.julia/packages/JSON3/czMzK/src/structs.jl:34
 [6] read(str::String, ::Type{S})
   @ JSON3 ~/.julia/packages/JSON3/czMzK/src/structs.jl:33
 [7] top-level scope
   @ show.jl:955
in expression starting at /tmp/mnwe.jl:12

alhirzel avatar Apr 05 '21 16:04 alhirzel