Jill-Jênn Vie
Jill-Jênn Vie

Reputation: 1841

Force YAML values to be strings

Look at this code, under Python 2.7:

>>> import yaml
>>> yaml.load('string: 01')
{'string': 1}
>>> :(

Is it possible to obtain the string 01 without modifying the yaml file? I didn't find anything in the docs.

Upvotes: 7

Views: 4118

Answers (2)

Camilo Abboud
Camilo Abboud

Reputation: 919

I was seeking for exactly the opposite effect: Numbers where being converted to stings, but numbers where wanted. I was using accidentally the BaseLoader (Dame copy-paste!).

The LOADER is the answer, as already stated by @Konrad Hałas.

Force Strings:

yaml.load('string: 01', Loader=yaml.loader.BaseLoader)

Force Number: (Default)

yaml.load('string: 01', Loader=yaml.loader.SafeLoader)

Link about Deprecation and detail:

https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation

Upvotes: 1

Konrad Hałas
Konrad Hałas

Reputation: 5144

Try:

>> import yaml
>> yaml.load('string: 01', Loader=yaml.loader.BaseLoader)
{u'string': u'01'}

Upvotes: 10

Related Questions