When I load a number with e form a JSON dump with YAML, the number is loaded as a string and not a float.
I think this simple example can explain my problem.
import json
import yaml
In [1]: import json
In [2]: import yaml
In [3]: All = {'one':1,'low':0.000001}
In [4]: jAll = json.dumps(All)
In [5]: yAll = yaml.safe_load(jAll)
In [6]: yAll
Out[6]: {'low': '1e-06', 'one': 1}
YAML loads 1e-06 as a string and not as a number? How can I fix it?
The problem lies in the fact that the YAML Resolver is set up to match floats as follows:
whereas the YAML spec specifies the regex for scientific notation as:
the latter makes the dot optional, which it isn't the above
re.compile()
pattern.The matching of floats can be fixed so it will accept floating point values with an
e
/E
but without decimal dot and with exponents without sign (i.e.+
implied):results in:
There is discrepancy between what JSON allows in numbers and the regex in the YAML 1.2 spec (concerning the required dot in the number and
e
being lower case). The JSON specification is IMO very clear in that it doesn't require the dot before 'e/E' nor that is requires a sign after the 'e/E':The PyYAML implementation does match floats partially according to the JSON spec and partially against the regex and fails on numbers that should be valid.
ruamel.yaml (which is my enhanced version of PyYAML), has these updated pattern and works correctly:
with output:
ruamel.yaml also accepts the number '1.0e6', which PyYAML also sees as a string.