Skip to content

MethodError when parsing JSON with nested Union types in Tuple field #436

@srMemphis

Description

@srMemphis

title: "MethodError when parsing JSON with nested Union types in Tuple field"

Description

When attempting to parse JSON into a struct containing a Tuple with complex nested Union types, JSON.jl fails with a MethodError about converting Vector{Any} to Union{Float64, Vector{Float64}}.

Minimum Working Example

using JSON

struct foo
    params::Tuple{Union{Float64, Nothing}, Union{Vector{Float64}, Float64}, Union{Vector{Float64}, Float64, Nothing}}
end

# This fails
JSON.parse("""{"params":[null, [1.0, 2.0, 3.0], null]}""", foo)

Error

ERROR: LoadError: MethodError: Cannot `convert` an object of type 
  Vector{Any} to an object of type
  Union{Float64, Vector{Float64}}
The function `convert` exists, but no method is defined for this combination of argument types.

Expected Behavior
The JSON should successfully parse into a foo instance, similar to how JSON3.jl handles this case:

using JSON3

struct foo
    params::Tuple{Union{Float64, Nothing}, Union{Vector{Float64}, Float64}, Union{Vector{Float64}, Float64, Nothing}}
end

# This works in JSON3.jl
JSON3.read("""{"params":[null, [1.0, 2.0, 3.0], null]}""", foo)
# Expected result: foo((nothing, [1.0, 2.0, 3.0], nothing))

Environment
JSON.jl version: 1.4.0
Julia version: 1.12.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions