How do I parse a yaml string with python?

30,792

Solution 1

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

Solution 2

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}
Share:
30,792
gae123
Author by

gae123

Updated on January 04, 2020

Comments

  • gae123
    gae123 over 4 years

    I see an API and many examples on how to parse a yaml file but what about a string?

  • Nikhil Talreja
    Nikhil Talreja over 4 years
    When I use this method, the type of dct is still string
  • Tomas Tomecek
    Tomas Tomecek over 4 years
    you should use yaml.safe_load for untrusted inputs
  • Johannes
    Johannes about 3 years
    if you need to install the library, be aware that it is pip install pyyaml but import yaml