pyyaml

Error when inserting a UUID into YAML using "!!python/object"


For an automated test script, I would like to generate random UUID values at runtime, so I added some YAML that looks like this:

---
applicant:
  idNumbers:
    nationalId: !!python/object:uuid.uuid4

However, this generates an error when I try to yaml.load the value:

ConstructorError: expected a mapping node, but found scalar
  in "<unicode string>", line 4, column 17:
        nationalId: !!python/object:uuid.uuid4
                    ^

How do I inject a UUID value via YAML tags?


Solution

  • I found the error message a bit intimidating at first, but after some thought, I was able to unpack it.

    The parser is expecting a "mapping" node, not a scalar. So, what happens if I add a mapping?

    >>> yaml.load('''---
    ... applicant:
    ...   idNumbers:
    ...     nationalId: !!python/object:uuid.uuid4 {}''')
    {'applicant': {'idNumbers': {'nationalId': UUID('71e09d1d-e84e-4ea6-855d-be1a2e91b60a')}}}
    

    Additional info: http://yaml.org/type/map.html