Search code examples
pythonpython-2.7yamlpyyaml

Disable PyYAML value conversion


I have just started to use PyYAML to convert some data.

I just use the yaml.load function and it was good enough for me until I noticed that it tries to convert all values to uni-coded string, int, dates and so on.

This could be fatal in my application, is there a way to avoid this conversion? I would like to receive everything as strings. I looked at the constructors and could not find a way to disable this conversion.

update: What I get from yaml.load is an OrderedDict and everything looks good. the only problem is that some values are string, and some are int. I would like to have all values as strings. I don´t want pyyaml to convert the values for me.


Solution

  • Well, you could use Loader=yaml.BaseLoader to leave everything as a string:

    >>> x = [[1,2,3], {1:2}]
    >>> s = yaml.dump(x)
    >>> s
    '- [1, 2, 3]\n- {1: 2}\n'
    >>> yaml.load(s)
    [[1, 2, 3], {1: 2}]
    >>> yaml.load(s, Loader=yaml.BaseLoader)
    [[u'1', u'2', u'3'], {u'1': u'2'}]