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

Yams should fail if there are duplicate keys in a mapping #415

Open
tejassharma96 opened this issue May 2, 2024 · 0 comments · May be fixed by #416
Open

Yams should fail if there are duplicate keys in a mapping #415

tejassharma96 opened this issue May 2, 2024 · 0 comments · May be fixed by #416

Comments

@tejassharma96
Copy link
Contributor

I recently encountered a bug when using Yams to read and write some yaml, and realized that the cause was a duplicate key in my yaml file that was being handled silently.

Per the yaml spec:

The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique. YAML places no further restrictions on the nodes. In particular, keys may be arbitrary nodes, the same node may be used as the value of several key: value pairs, and a mapping could even contain itself as a key or a value (directly or indirectly).

Basically, duplicate keys are not allowed. Yams should recognize when there is a duplicate key in a mapping and throw an error rather than having undefined behaviour (I think it just picks the version that is lowest in the file).

As an example:

import Foundation
import Yams

struct MyCodable: Codable {
    let thing: String
}

let yaml = """
key:
  thing: hello
key:
  thing: goodbye
"""

let data = Data(yaml.utf8)

let decoder = YAMLDecoder()
let test = try decoder.decode([String: MyCodable].self, from: data)
print(test)

prints ["key": __lldb_expr_7.MyCodable(thing: "goodbye")] - it doesn't throw any errors and selects the key that is lower in the text.

@tejassharma96 tejassharma96 linked a pull request May 6, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant