Skip to content

Commit dd7d489

Browse files
authored
Treat array of pairs as object when writing. Fixes #398 (#406)
1 parent 2990e03 commit dd7d489

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

src/write.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ StructUtils.lower(::JSONStyle, x::Regex) = x.pattern
1515
StructUtils.lower(::JSONStyle, x::AbstractArray{<:Any,0}) = x[1]
1616
StructUtils.lower(::JSONStyle, x::AbstractArray{<:Any, N}) where {N} = (view(x, ntuple(_ -> :, N - 1)..., j) for j in axes(x, N))
1717
StructUtils.lower(::JSONStyle, x::AbstractVector) = x
18+
StructUtils.arraylike(::JSONStyle, x::AbstractVector{<:Pair}) = false
1819

1920
# for pre-1.0 compat, which serialized Tuple object keys by default
2021
StructUtils.lowerkey(::JSONStyle, x::Tuple) = string(x)

test/json.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,13 @@ end
8181
@test JSON.json(Dict{Int, Int}(1 => 2)) == "{\"1\":2}"
8282
@test JSON.json((a = 1, b = 2)) == "{\"a\":1,\"b\":2}"
8383
@test JSON.json((a = nothing, b=2, c="hey", d=3.14, e=true, f=false)) == "{\"a\":null,\"b\":2,\"c\":\"hey\",\"d\":3.14,\"e\":true,\"f\":false}"
84+
# test Vector{Pair} serializes as object, not array
85+
@test JSON.json(Pair{String, Int}[]) == "{}"
86+
@test JSON.json([:a => 1, :b => 2]) == "{\"a\":1,\"b\":2}"
87+
@test JSON.json(["x" => "value", "y" => 42]) == "{\"x\":\"value\",\"y\":42}"
88+
@test JSON.json([1 => "one", 2 => "two"]) == "{\"1\":\"one\",\"2\":\"two\"}"
89+
# test Vector{Pair} in nested structures
90+
@test JSON.json(Dict("data" => [:x => 1, :y => 2])) == "{\"data\":{\"x\":1,\"y\":2}}"
8491
# test the JSON output of nested array/objects
8592
@test JSON.json([1, [2, 3], [4, [5, 6]]]) == "[1,[2,3],[4,[5,6]]]"
8693
@test JSON.json(Dict{Int, Any}(1 => Dict{Int, Any}(2 => Dict{Int, Any}(3 => 4)))) == "{\"1\":{\"2\":{\"3\":4}}}"

0 commit comments

Comments
 (0)