From edacd0bd465f1f2ece040caa7c78475b12ace489 Mon Sep 17 00:00:00 2001 From: Daniel Thom Date: Wed, 20 Jul 2022 19:07:56 -0600 Subject: [PATCH] Add option to pretty-print JSON text --- src/serialization.jl | 14 +++++++++++--- test/test_serialization.jl | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/serialization.jl b/src/serialization.jl index 9485b03f4..53dc767f3 100644 --- a/src/serialization.jl +++ b/src/serialization.jl @@ -13,12 +13,13 @@ function to_json( obj::T, filename::AbstractString; force=false, + pretty=false, ) where {T <: InfrastructureSystemsType} if !force && isfile(filename) error("$file already exists. Set force=true to overwrite.") end result = open(filename, "w") do io - return to_json(io, obj) + return to_json(io, obj, pretty=pretty) end @info "Serialized $T to $filename" @@ -28,10 +29,15 @@ end """ Serializes a InfrastructureSystemsType to a JSON string. """ -function to_json(obj::T)::String where {T <: InfrastructureSystemsType} +function to_json(obj::T) where {T <: InfrastructureSystemsType} return JSON3.write(serialize(obj)) end +function to_json(io::IO, obj::T; pretty=false) where {T <: InfrastructureSystemsType} + func = pretty ? JSON3.pretty : JSON3.write + return func(io, serialize(obj)) +end + """ Deserializes a InfrastructureSystemsType from a JSON filename. """ @@ -74,7 +80,9 @@ end function serialize_struct(val::T) where {T} @debug "serialize_struct" _group = LOG_GROUP_SERIALIZATION val T - data = Dict(string(name) => serialize(getfield(val, name)) for name in fieldnames(T)) + data = Dict{String, Any}( + string(name) => serialize(getfield(val, name)) for name in fieldnames(T) + ) add_serialization_metadata!(data, T) return data end diff --git a/test/test_serialization.jl b/test/test_serialization.jl index dc2072fe0..8484efa3a 100644 --- a/test/test_serialization.jl +++ b/test/test_serialization.jl @@ -93,3 +93,24 @@ end @test haskey(data, "julia_version") @test haskey(data, "package_info") end + +@testset "Test JSON string" begin + component = IS.TestComponent("Component1", 1) + text = IS.to_json(component) + IS.deserialize(IS.TestComponent, JSON3.read(text, Dict)) == component +end + +@testset "Test pretty-print JSON IO" begin + component = IS.TestComponent("Component1", 2) + io = IOBuffer() + IS.to_json(io, component, pretty=false) + text = String(take!(io)) + @test !occursin(" ", text) + IS.deserialize(IS.TestComponent, JSON3.read(text, Dict)) == component + + io = IOBuffer() + IS.to_json(io, component, pretty=true) + text = String(take!(io)) + @test occursin(" ", text) + IS.deserialize(IS.TestComponent, JSON3.read(text, Dict)) == component +end