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

Using custom tags as keys? #46

Closed
julien-c opened this issue Nov 20, 2018 · 3 comments
Closed

Using custom tags as keys? #46

julien-c opened this issue Nov 20, 2018 · 3 comments

Comments

@julien-c
Copy link

Thanks for this library, this looks awesome and I'm going to play with it a bit.

Can we use custom tags as keys? i.e.:

foo:
    !bar: Hello
@eemeli
Copy link
Owner

eemeli commented Nov 21, 2018

Yes, custom tags are supported. To use them with YAML.parse, you'll need to define them in YAML.defaultOptions.tags, but with YAML.parseDocument you can get the AST and handle it yourself. Note that there'll be an entry in doc.warnings about the fallback to string due to the missing tag.

Just to clarify your example, according to the spec it's parsed as a mapping with a key foo and a value Hello that has the tag !bar:. If there was a space before the :, the value would be parsed as a mapping with an empty key that has the tag !bar, and the value Hello. Is one of those what you intended to mean?

@julien-c
Copy link
Author

No I don't think so 😕

What I'm looking for is something that would parse to something like (in pseudo-JS code):

{
  foo: new Map([
    [ new Baz, 'Hello' ]
  ])
}

Not sure this can even be expressed in yaml though.

@eemeli
Copy link
Owner

eemeli commented Nov 27, 2018

Yes, that can be represented in YAML. What you're looking for is a custom schema for your data, i.e. a way of telling the parser that this particular thing should be represented by a Map, and this other thing by a Baz.

For Map you'd probably want to customise the built-in !!map parser's toJSON method to produce a Map rather than an Object. Arguably this would make sense to implement as a configurable option, for which I'll add a separate issue. In the meantime, you can avoid the string-key issue by using YAML.parseDocument rather than YAML.parse, as the internal representation of a map does not have this issue.

For Baz a custom local tag like !baz is the right answer. To implement that, take a look at how e.g. the !!binary tag is implemented; there's a link from the Custom tags section of the docs. If you don't need to stringify your data, you don't need to implement a stringify() function, just the resolve().

With all of that, you'd end up with this YAML representation of your data:

foo:
  !baz : Hello

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.

2 participants