The JSON.json
function serializes a Julia object into a Julia String
containing JSON:
julia> using JSON
julia> JSON.json(Dict(:a => :b, :c => [1, 2, 3.0], :d => nothing))
"{\"c\":[1.0,2.0,3.0],\"a\":\"b\",\"d\":null}"
julia> println(ans)
{"c":[1.0,2.0,3.0],"a":"b","d":null}
If a string is not desired, JSON can be printed directly to an IO stream:
julia> JSON.print(STDOUT, [1, 2, true, false, "x"])
[1,2,true,false,"x"]
Note that STDOUT
is the default, and can be omitted in the above call.
Prettier printing can be achieved by passing the optional indent
parameter:
julia> JSON.print(STDOUT, Dict(:a => :b, :c => :d), 4)
{
"c": "d",
"a": "b"
}
There is a sane default serialization for complex Julia types:
julia> immutable Point3D
x::Float64
y::Float64
z::Float64
end
julia> JSON.print(Point3D(1.0, 2.0, 3.0), 4)
{
"y": 2.0,
"z": 3.0,
"x": 1.0
}