Skip to content

Commit

Permalink
Merge pull request #292 from daniel-thom/pretty-json
Browse files Browse the repository at this point in the history
Add option to pretty-print JSON text
  • Loading branch information
jd-lara authored Jul 22, 2022
2 parents 4e517d5 + edacd0b commit 386f870
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/serialization.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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.
"""
Expand Down Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions test/test_serialization.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 386f870

Please sign in to comment.