How do I parse a yaml string with python?

Question:

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

Asked By: gae123

||

Answers:

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
Answered By: gae123

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}
Answered By: Tomas Tomecek
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.