I see an API and many examples on how to parse a yaml file but what about a string?
We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.
However, Python lacks built-in support for the YAML data format, commonly used for configuration and serialization, despite clear similarities between the two languages. In this tutorial, you'll learn how to work with YAML in Python using the available third-party libraries, with a focus on PyYAML.
Here is the best way I have seen so far demonstrated with an example:
import yaml dct = yaml.safe_load(''' name: John age: 30 automobiles: - brand: Honda type: Odyssey year: 2018 - brand: Toyota type: Sienna year: 2015 ''') assert dct['name'] == 'John' assert dct['age'] == 30 assert len(dct["automobiles"]) == 2 assert dct["automobiles"][0]["brand"] == "Honda" assert dct["automobiles"][1]["year"] == 2015
You don't need to wrap the string in StringIO, the safe_load
method accepts strings:
In [1]: yaml.safe_load("{1: 2}") Out[1]: {1: 2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With