Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,12 @@ YAML.load("speed: !unit/kmh 80", nothing, units) # Dict("speed" => ("kmh", "80")

Similar to reading files, you can emit Julia objects to YAML files by calling
`write_file`, or to a string object by calling `write`. Tuples and sets are
written as sequences, `missing` as null like `nothing`, and a rational as the
nearest float, because YAML has no rational type.
written as sequences, named tuples as mappings, `missing` as null like
`nothing`, and rationals and irrationals such as `π` as the nearest float,
because YAML has no type for them. A complex number is written as a mapping
with keys `re` and `im`. Dictionary keys that are not text are written as their
values would be, and a nonempty collection key as an explicit `?` key, so a
`Dict((1, 2) => 3)` loads back as `Dict([1, 2] => 3)`.

For example, you can reproduce the above file from the variable `data`

Expand Down
41 changes: 30 additions & 11 deletions src/writer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,19 @@ const Sequence = Union{AbstractVector,Tuple,AbstractSet}
_print(io::IO, x::Union{Tuple,AbstractSet}, level::Int=0, ignore_level::Bool=false) =
_print(io, collect(x), level, ignore_level)

# Julia values written as YAML mappings. A `Pair` is a one-entry mapping. YAML has no complex
# type, so a complex number is written as its parts, as JSON.jl does.
const Mapping = Union{AbstractDict,NamedTuple,Complex,Pair}

_print(io::IO, x::NamedTuple, level::Int=0, ignore_level::Bool=false) =
_print(io, pairs(x), level, ignore_level)

_print(io::IO, z::Complex, level::Int=0, ignore_level::Bool=false) =
_print(io, (re = real(z), im = imag(z)), level, ignore_level)

# a nonempty collection key or value starts on the line after its '?' or key
starts_block(x) = x isa Union{Mapping,Sequence} && !isempty(x)

# recursively print an array
function _print(io::IO, arr::AbstractVector, level::Int=0, ignore_level::Bool=false)
if isempty(arr)
Expand All @@ -78,16 +91,22 @@ end
# print a single key-value pair
function _print(io::IO, pair::Pair, level::Int=0, ignore_level::Bool=false)
k = pair[1] isa Union{Symbol,AbstractChar} ? string(pair[1]) : pair[1] # text keys are strings
key = if k === nothing || k === missing
"null" # this is what the YAML parser interprets as 'nothing'
elseif k isa AbstractString && string_key_needs_quoting(k)
string("\"", escape_yaml_string(k), "\"") # special keys that require quoting
if starts_block(k)
# a collection key is written as an explicit key: '?', the key's lines, then ':'
println(io, _indent("?", level, ignore_level))
_print(io, k, level + 1)
print(io, _indent(":", level))
else
string(k) # any "normal" case
key = if k === nothing || k === missing
"null" # this is what the YAML parser interprets as 'nothing'
elseif k isa AbstractString
string_key_needs_quoting(k) ? string("\"", escape_yaml_string(k), "\"") : k
else
chomp(sprint(_print, k)) # other keys are written as values are, such as .inf or []
end
print(io, _indent(key * ":", level, ignore_level)) # print the key
end

print(io, _indent(key * ":", level, ignore_level)) # print the key
if (pair[2] isa AbstractDict || pair[2] isa Sequence) && !isempty(pair[2])
if starts_block(pair[2])
print(io, "\n") # a line break is needed before a recursive structure
else
print(io, " ") # a whitespace character is needed before a single value
Expand Down Expand Up @@ -176,9 +195,9 @@ end
_print(io::IO, val::Union{Nothing,Missing}, level::Int=0, ignore_level::Bool=false) =
println(io, "~") # this is what the YAML parser interprets as nothing

# YAML has no rational type, so a rational is written as the nearest float, which every reader
# loads as a number
_print(io::IO, val::Rational, level::Int=0, ignore_level::Bool=false) =
# YAML has no rational or irrational type, so these are written as the nearest float, which
# every reader loads as a number
_print(io::IO, val::Union{Rational,AbstractIrrational}, level::Int=0, ignore_level::Bool=false) =
_print(io, float(val), level, ignore_level)

# Symbols and Chars hold text, so they are written as strings
Expand Down
24 changes: 24 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,30 @@ end
@test YAML.load(YAML.yaml(Dict(missing => 1))) == Dict(nothing => 1)
end

@testset "named tuples, irrationals, complex numbers, and non-string keys load back" begin
for (x, expected) in (((a = 1, b = "x: y"), Dict("a" => 1, "b" => "x: y")), (NamedTuple(), Dict()),
((a = (b = [1, 2],),), Dict("a" => Dict("b" => [1, 2]))), (pi, Float64(pi)),
(1 + 2im, Dict("re" => 1, "im" => 2)), (1.5 - Inf*im, Dict("re" => 1.5, "im" => -Inf)))
@test isequal(YAML.load(YAML.yaml(x)), expected)
@test isequal(YAML.load(YAML.yaml(Dict("k" => x))), Dict("k" => expected))
@test isequal(YAML.load(YAML.yaml([x])), [expected])
end
# keys are written as values are; a nonempty collection key is written as an explicit '?' key
for (k, expected) in ((1.5, 1.5), (Inf, Inf), (NaN, NaN), (1e300, 1e300), (1//2, 0.5), (pi, Float64(pi)),
((1, 2), [1, 2]), ((1, "a: b"), [1, "a: b"]), ([1, 2], [1, 2]), ((), []),
(Dict("a" => 1), Dict("a" => 1)), ((a = 1,), Dict("a" => 1)), (1 + 2im, Dict("re" => 1, "im" => 2)))
@test isequal(YAML.load(YAML.yaml(Dict(k => 1))), Dict(expected => 1))
@test isequal(YAML.load(YAML.yaml(Dict(k => [Dict("v" => 1)]))), Dict(expected => [Dict("v" => 1)]))
@test isequal(YAML.load(YAML.yaml(Dict("k" => Dict(k => 1)))), Dict("k" => Dict(expected => 1)))
@test isequal(YAML.load(YAML.yaml([Dict(k => 1, "z" => 2)])), [Dict(expected => 1, "z" => 2)])
end
end

@testset "Pair keys and values are written as one-entry mappings" begin
@test YAML.load(YAML.yaml(Dict((1 => 2) => 3))) == Dict(Dict(1 => 2) => 3)
@test YAML.load(YAML.yaml(Dict("a" => (1 => 2)))) == Dict("a" => Dict(1 => 2))
end

@testset "flow scalar line folding" begin
for linebreak in ("\n", "\r\n", "\r", "\u0085"), delimiter in ("'", "\"", "")
for (count, expected) in ((1, "first second"), (2, "first\nsecond"), (3, "first\n\nsecond"))
Expand Down
Loading