Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue with special keys that require quoting in mappings #237

Merged
merged 3 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 12 additions & 0 deletions src/writer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,21 @@ 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]) ||
any(
c -> startswith(pair[1], c),
[
'{', '}', '[', ']', '&', '*', '#', '?', '|', '-', '<', '>', '=',
'!', '%', '@', ':', '`', ',', '"', '\'',
],
)
kescobo marked this conversation as resolved.
Show resolved Hide resolved
)
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
10 changes: 10 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -491,4 +491,14 @@ 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 YAML.load(YAML.yaml(Dict(string(char) => 0.0))) == Dict(char => 0.0)
dalum marked this conversation as resolved.
Show resolved Hide resolved
end
end

end # module
Loading