From b53caddff8bbe9f01df7b03ff0cd4a24e73e5bda Mon Sep 17 00:00:00 2001 From: Jacob Quinn Date: Thu, 14 May 2026 14:19:20 -0600 Subject: [PATCH] feat(write): serialize complex numbers Fixes #440 --- src/write.jl | 1 + test/json.jl | 3 +++ 2 files changed, 4 insertions(+) diff --git a/src/write.jl b/src/write.jl index 5148aa8..5262175 100644 --- a/src/write.jl +++ b/src/write.jl @@ -35,6 +35,7 @@ StructUtils.lower(::JSONStyle, ::Missing) = nothing StructUtils.lower(::JSONStyle, x::Symbol) = String(x) StructUtils.lower(::JSONStyle, x::StringLike) = string(x) StructUtils.lower(::JSONStyle, x::Regex) = x.pattern +StructUtils.lower(::JSONStyle, x::Complex) = (re=real(x), im=imag(x)) StructUtils.lower(::JSONStyle, x::AbstractArray{<:Any,0}) = x[1] StructUtils.lower(::JSONStyle, x::AbstractArray{<:Any, N}) where {N} = (view(x, ntuple(_ -> :, N - 1)..., j) for j in axes(x, N)) StructUtils.lower(::JSONStyle, x::AbstractVector) = x diff --git a/test/json.jl b/test/json.jl index 38c8ebf..a6f0157 100644 --- a/test/json.jl +++ b/test/json.jl @@ -244,6 +244,9 @@ end @test_throws MethodError JSON.json(CustomNumber(3.14)) JSON.tostring(x::CustomNumber) = string(x.x) @test JSON.json(CustomNumber(3.14)) == "3.14" + # https://github.com/JuliaIO/JSON.jl/issues/440 + @test JSON.json(1 + 2im) == "{\"re\":1,\"im\":2}" + @test JSON.parse(JSON.json(1.0 + 2.0im), ComplexF64) == 1.0 + 2.0im # jsonlines output @test JSON.json([1, 2, 3]; jsonlines=true) == "1\n2\n3\n" # jsonlines output with pretty not allowed