Skip to content

Commit b3e8dce

Browse files
authored
Support UUID and other stringlike types as keys (#435)
1 parent de651ce commit b3e8dce

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

src/write.jl

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,11 @@ sizeguess(::Null) = 4
2929
sizeguess(::Omit) = 0
3030
sizeguess(_) = 512
3131

32+
const StringLike = Union{Enum, AbstractChar, VersionNumber, Cstring, Cwstring, UUID, Dates.TimeType, Type, Logging.LogLevel}
33+
3234
StructUtils.lower(::JSONStyle, ::Missing) = nothing
3335
StructUtils.lower(::JSONStyle, x::Symbol) = String(x)
34-
StructUtils.lower(::JSONStyle, x::Union{Enum, AbstractChar, VersionNumber, Cstring, Cwstring, UUID, Dates.TimeType, Type, Logging.LogLevel}) = string(x)
36+
StructUtils.lower(::JSONStyle, x::StringLike) = string(x)
3537
StructUtils.lower(::JSONStyle, x::Regex) = x.pattern
3638
StructUtils.lower(::JSONStyle, x::AbstractArray{<:Any,0}) = x[1]
3739
StructUtils.lower(::JSONStyle, x::AbstractArray{<:Any, N}) where {N} = (view(x, ntuple(_ -> :, N - 1)..., j) for j in axes(x, N))
@@ -250,9 +252,8 @@ end
250252

251253
StructUtils.lowerkey(::JSONStyle, s::AbstractString) = s
252254
StructUtils.lowerkey(::JSONStyle, sym::Symbol) = String(sym)
253-
StructUtils.lowerkey(::JSONStyle, n::Union{Integer, Union{Float16, Float32, Float64}}) = string(n)
255+
StructUtils.lowerkey(::JSONStyle, s::Union{StringLike, Real}) = string(s)
254256
StructUtils.lowerkey(::JSONStyle, x) = throw(ArgumentError("No key representation for $(typeof(x)). Define StructUtils.lowerkey(::JSON.JSONStyle, ::$(typeof(x)))"))
255-
256257
"""
257258
JSON.json(x) -> String
258259
JSON.json(io, x)

test/json.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ end
2727
dropped::Union{Nothing, JSON.Omit}
2828
end
2929

30+
@enum JsonFruit Apple Orange
31+
3032
@testset "JSON.json" begin
3133

3234
@testset "Basics" begin
@@ -261,6 +263,18 @@ end
261263
@test JSON.json((a=1, b=nothing); omit_null=false) == "{\"a\":1,\"b\":null}"
262264
@test JSON.json((a=1, b=[]); omit_empty=true) == "{\"a\":1}"
263265
@test JSON.json((a=1, b=[]); omit_empty=false) == "{\"a\":1,\"b\":[]}"
266+
@testset "All string-like types as keys" begin
267+
date = Dates.DateTime(1970)
268+
@test JSON.json([
269+
UUID(0) => "uuid",
270+
'c' => "char",
271+
v"0.0.1" => "ver",
272+
Apple => "Enum 1",
273+
Orange => "Enum 2",
274+
date => "date"
275+
]) == """{"00000000-0000-0000-0000-000000000000":"uuid","c":"char","0.0.1":"ver","Apple":"Enum 1","Orange":"Enum 2","1970-01-01T00:00:00":"date"}"""
276+
end
277+
264278
@testset "Sentinel overrides" begin
265279
@test JSON.json(JSON.Null()) == "null"
266280
@test_throws ArgumentError JSON.json(JSON.Omit())

0 commit comments

Comments
 (0)