From 3edf12e44bdcfc0216b884aa84cfd3ef836a8fab Mon Sep 17 00:00:00 2001 From: Jacob Quinn Date: Wed, 18 Nov 2026 04:44:34 -0700 Subject: [PATCH 1/3] Test that named tuples, irrationals, complex numbers, and non-string keys load back Co-Authored-By: Claude Opus 5.5 --- test/runtests.jl | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/runtests.jl b/test/runtests.jl index 5b673fc..ba1c9d8 100755 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -689,6 +689,25 @@ 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 "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")) From f998cf6bfa3743528d22e5efcf97e0e638f96dec Mon Sep 17 00:00:00 2001 From: Jacob Quinn Date: Wed, 18 Nov 2026 04:46:04 -0700 Subject: [PATCH 2/3] Write named tuples, complex numbers, irrationals, and non-string keys as YAML values Named tuples, complex numbers, and irrationals fell through to string(), and keys other than text used string(k). They loaded back as Julia text, and a tuple key holding ': ' gave YAML that didn't load. Named tuples are now written as mappings, complex numbers as a re/im mapping (JSON.jl's form), irrationals as the nearest float, scalar keys as their values would be, and collection keys as explicit '?' keys. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++++-- src/writer.jl | 41 ++++++++++++++++++++++++++++++----------- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 6ba45da..3945eb8 100644 --- a/README.md +++ b/README.md @@ -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` diff --git a/src/writer.jl b/src/writer.jl index f9c6d9f..08a642e 100644 --- a/src/writer.jl +++ b/src/writer.jl @@ -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. YAML has no complex type, so a complex number is +# written as its parts, as JSON.jl does. +const Mapping = Union{AbstractDict,NamedTuple,Complex} + +_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) @@ -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 @@ -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 From 703aac160813aa6c6fbe8ebc783c92cf0f57269f Mon Sep 17 00:00:00 2001 From: Jacob Quinn Date: Wed, 18 Nov 2026 05:41:45 -0700 Subject: [PATCH 3/3] Write a Pair as a one-entry mapping A Pair key was written as "1: 2: 3", which doesn't load. Treating Pair as a mapping writes it with an explicit '?' key when it is a key and as a nested mapping when it is a value, and both load back. Co-Authored-By: Claude Opus 5.5 --- src/writer.jl | 6 +++--- test/runtests.jl | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/writer.jl b/src/writer.jl index 08a642e..5127134 100644 --- a/src/writer.jl +++ b/src/writer.jl @@ -58,9 +58,9 @@ 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. YAML has no complex type, so a complex number is -# written as its parts, as JSON.jl does. -const Mapping = Union{AbstractDict,NamedTuple,Complex} +# 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) diff --git a/test/runtests.jl b/test/runtests.jl index ba1c9d8..52637dd 100755 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -708,6 +708,11 @@ end 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"))