How do I parse a yaml string with python?
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}
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