Skip to content

Commit

Permalink
Merge pull request #237 from dalum/master
Browse files Browse the repository at this point in the history
Fix issue with special keys that require quoting in mappings
  • Loading branch information
kescobo authored Jul 18, 2024
2 parents 2bf3845 + f79440f commit c6ac0b3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/writer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,14 @@ end
function _print(io::IO, pair::Pair, level::Int=0, ignore_level::Bool=false)
key = if pair[1] === nothing
"null" # this is what the YAML parser interprets as 'nothing'
elseif pair[1] isa AbstractString && (
occursin('#', pair[1]) || first(pair[1]) in "{}[]&*?|-<>=!%@:`,\"'"
)
string("\"", escape_string(pair[1]), "\"") # special keys that require quoting
else
string(pair[1]) # any useful case
end

print(io, _indent(key * ":", level, ignore_level)) # print the key
if (pair[2] isa AbstractDict || pair[2] isa AbstractVector) && !isempty(pair[2])
print(io, "\n") # a line break is needed before a recursive structure
Expand Down
15 changes: 15 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -473,4 +473,19 @@ end
@test collect(YAML.load_all(input)) == expected
end

# issue #236 - special string keys that require enclosure in quotes
@testset "issue #236" begin
for char in "{}[]&*?#|-<>=!%@:`,\"'"
test_case_1 = Dict(string(char) => 0.0)
test_case_2 = Dict(string(char, "abcd") => 0.0)
test_case_3 = Dict(string("abcd", char) => 0.0)
test_case_4 = Dict(string("abcd", char, "efgh") => 0.0)

@test YAML.load(YAML.yaml(test_case_1)) == test_case_1
@test YAML.load(YAML.yaml(test_case_2)) == test_case_2
@test YAML.load(YAML.yaml(test_case_3)) == test_case_3
@test YAML.load(YAML.yaml(test_case_4)) == test_case_4
end
end

end # module

0 comments on commit c6ac0b3

Please sign in to comment.