JuliaIO / JSON.jl

JSON parsing and printing
Other
313 stars 101 forks source link

JSON.jl Float64 serialization (suppress scientific notation) #367

Open tamasgal opened 1 month ago

tamasgal commented 1 month ago

I am having a hard time with JSON.jl. I want to serialize large Float64 instances without scientific notation and the only way I was able to get at least the rounding working results in a string, instead of a float value ;) I am reposting it from Discourse since I feel like it's a too specific question and might be better discussed here.

using Printf
using JSON
import JSON.Serializations: CommonSerialization, StandardSerialization
import JSON.Writer: StructuralContext, show_json

struct RoundedFloatSerialization <: CommonSerialization end

show_json(io::StructuralContext,
            ::RoundedFloatSerialization,
           f::AbstractFloat) =
    show_json(io, StandardSerialization(), @sprintf("%.3f", f))

Here is an example which shows that 1e4 is serialized to 10000.0 by default, whereas 1e9 to 1.0e9. The hook into the show_json works, but it yields a String for obvious reasons, see below an example.

julia> JSON.json(1e4)
"10000.0"

julia> JSON.json(1e9)
"1.0e9"

julia> sprint(show_json, RoundedFloatSerialization(), 1e4)
"\"10000.000\""

julia> sprint(show_json, RoundedFloatSerialization(), 1e9)
"\"1000000000.000\""

Where should I intercept the scientific notation for large floats without being a pirate? :pirate_flag: