How to load yaml into a python class object with UnsafeLoader
0
Contents
Here is a pyyaml
code snippet that writes a python class object to yaml file and then also loads the yaml file back to python class object.
Warning: Using yaml.UnsafeLoader is not safe and could lead to security issues such as arbitrary code execution.
Source Code
import yaml # pip install pyyaml
# Define a custom class
class PersonClass:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def __str__(self):
return repr(self)
# Create an instance of the person class
obj = PersonClass("Jane Doe", 33, "Female")
# Try to serialize the object to YAML
try:
print(yaml.dump(obj))
except yaml.RepresenterError as e:
print("RepresenterError:", e)
how to load yaml into a python class object with yaml.UnsafeLoader
myobj = yaml.load("""!!python/object:__main__.PersonClass
age: 24
gender: Male
name: John Doe
""", Loader=yaml.UnsafeLoader) # Parse the first YAML document in a stream and produce the corresponding Python object.
# Access the attributes of the object
print(myobj.name)
print(myobj.age)
# Serialize the object back to YAML
print(yaml.dump(myobj))
Potential pyyaml errors
yaml.constructor.ConstructorError: could not determine a constructor for the tag ’tag:yaml.org,2002:python/object:main.PersonClass'
TypeError: load() missing 1 required positional argument: ‘Loader’
About PyYAML
PyYAML - A YAML parser and emitter for Python.