Nick Humrich
Nick Humrich

Reputation: 15785

Force YAML to format string as a quoted string

I have the following string "058" that I need to dump into YAML, but when I do a dump, it gets converted into a "number". (no quotes). All other number-like strings seem to work fine.

yaml.dump({'a': '058'})

returns:

'a: 058\n'

as you will notice, the string doesn't have the quote around it. Compare to another number:

yaml.dump({'a': '057'})

returns:

"a: '057'\n"

and that one has the single quotes around the string. Every other number I have tested does the quotes except for '058'.

How do I force YAML to have the quotes around it?

Upvotes: 2

Views: 1638

Answers (2)

magma
magma

Reputation: 299

There are certain regular expressions defined in yaml library. Of course their purpose is to parse popular formats (i.a octal numbers). The exact regexp that causes this behaviour is

[-+]?0[0-7_]+

To handle this problem you need to add custom explicit resolver, but keep in mind that oct values containing numbers from beyond the scope of 0-8 will be parsed improperly - that is like they were proper oct values.

And here's the solution:

import re
from yaml import dump
from yaml.resolver import Resolver

Resolver.add_implicit_resolver(
    'tag:yaml.org,2002:int',
    re.compile(r'''^([-+]?0[0-9_]+)$''', re.X),
    list('-+0123456789'))

yaml.dump({'a': '058'})

Then you'll get

"a: '058'\n"

Upvotes: 3

OneCricketeer
OneCricketeer

Reputation: 191914

It is a string. Quotes arent required in YAML; the value doesn't indicate an octal number

import yaml
from yaml import CLoader as Loader

yaml.load('a: 058\n', Loader=Loader)
#  {'a': '058'}
type(yaml.load('a: 058\n', Loader=Loader)['a'])
# str

Upvotes: 1

Related Questions