-
Notifications
You must be signed in to change notification settings - Fork 33
Description
Summary
When converting a YAML document containing strings that could represent numbers or dates, ConvertFrom-YAML will always convert them to numbers or dates.
Environment
- Windows 10 Pro x64
- Windows Powershell 5.1.15063.786
- PSYaml 1.0.2, installed via
Install-Package
Steps to reproduce
- Create a valid YAML document
- Add a string value which contains a number or a date
- Convert the document via
ConvertFrom-Yaml
Actual result
String values that look like numbers are dates are converted to number or date objects:
> $fromYaml = ConvertFrom-Yaml -YamlString @"
one: thing
two: "2"
three: "2014-04-01"
"@
> $fromYaml.two; $fromYaml.two.GetType().Name
2
Int32
> $fromYaml.three; $fromYaml.three.GetType().Name
Tuesday, April 1, 2014 12:00:00 AM
DateTime
Expected result
I expected that, just like with the native ConvertFrom-Json cmdlet, string values are preserved as strings, rather than converted to numbers or dates, as long as the values are wrapped in double quotes.
Here is similar output for the ConvertFrom-Json cmdlet, showing that strings are preserved:
> $fromJson = ConvertFrom-Json -InputObject '{"one": "thing", "two": "2", "three": "2014-04-01"}'
> $fromJson.two; $fromJson.two.GetType().Name
2
String
> $fromJson.three; $fromJson.three.GetType().Name
2014-04-01
String
For what it's worth, other YAML converters had my expected output, where strings are preserved. For instance, here is the PyYAML module for Python converting a YAML string into a Python dict:
>>> import yaml
>>> from_yaml = yaml.load("""
... one: thing
... two: "2"
... three: "2014-04-01"
... """)
>>> from_yaml['two']; type(from_yaml['two'])
'2'
<class 'str'>
>>> from_yaml['three']; type(from_yaml['three'])
'2014-04-01'
<class 'str'>
Workaround
Happily, there is a workaround for anyone else who might run into this. PSYaml supports YAML tags, as documented in the readme. If you have control over the input YAML document, you can prepend the !!str tag to the value that should remain a string, like so:
> $fromTaggedYaml = ConvertFrom-Yaml -YamlString @"
one: thing
two: !!str "2"
three: !!str "2014-04-01"
"@
> $fromTaggedYaml.two; $fromTaggedYaml.two.GetType().Name
2
String
> $fromTaggedYaml.three; $fromTaggedYaml.three.GetType().Name
2014-04-01
String