Skip to content

Commit

Permalink
Support for Nullable and Char (#174)
Browse files Browse the repository at this point in the history
* Support for `Nullable`

Added `_writejson` method for `Nullable` values. Maps to JSON `null` if
value is null.

* trying to fix test fail on 0.4

* Added  conversion

* Added more tests and converted `Char` handling to use `lower`
  • Loading branch information
joshbode authored and TotalVerb committed Oct 4, 2016
1 parent 624144b commit 0e36473
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/JSON.jl
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ if VERSION < v"0.5.0-dev+2396"
lower(f::Function) = "function at $(f.fptr)"
end

lower(c::Char) = string(c)
lower(d::DataType) = string(d)
lower(m::Module) = throw(ArgumentError("cannot serialize Module $m as JSON"))

Expand Down Expand Up @@ -167,6 +168,14 @@ function _writejson(io::IO, state::State, n::Void)
Base.print(io, "null")
end

function _writejson(io::IO, state::State, a::Nullable)
if isnull(a)
Base.print(io, "null")
else
_writejson(io, state, get(a))
end
end

function _writejson(io::IO, state::State, a::Associative)
if length(a) == 0
Base.print(io, "{}")
Expand Down
11 changes: 11 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,17 @@ end
@test sprint(JSON.print, [NaN]) == "[null]"
@test sprint(JSON.print, [Inf]) == "[null]"

# check Nullables are printed correctly
@test sprint(JSON.print, [Nullable()]) == "[null]"
@test sprint(JSON.print, [Nullable{Int64}()]) == "[null]"
@test sprint(JSON.print, [Nullable{Int64}(Int64(1))]) == "[1]"

# check Chars
@test json('a') == "\"a\""
@test json('\\') == "\"\\\\\""
@test json('\n') == "\"\\n\""
@test json('🍩') =="\"🍩\""

# check for issue #163
@test Float32(JSON.parse(json(2.1f-8))) == 2.1f-8

Expand Down

0 comments on commit 0e36473

Please sign in to comment.