49

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

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
gae123
  • 8,589
  • 3
  • 35
  • 40
  • 3
    What have you tried so far? – Klaus D. May 05 '18 at 05:58
  • 1
    FYI YAML is not safe. It is susceptible to vulnerabilities that allows the user to execute code on your servers https://www.youtube.com/watch?v=LrW-HSHP0ws – AlanSTACK May 05 '18 at 05:59
  • @AlanSTACK thanks for the heads up, I was looking for a quick way to try some things, in particular how multi-line strings are parsed in yaml. – gae123 May 05 '18 at 06:02
  • 5
    @KlausD. this remark would have been more appropriate if there was something obvious to try. `yaml.load/safe_load` is polymorphic in what it accepts, but if all the examples show files, leaves one to look for something else to handle strings, as json does it with `load`/`loads`. Hard to try using a function that doesn't exist and there's nothing wrong with ... just asking a question. – JL Peyret Aug 12 '20 at 07:03

2 Answers2

74

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
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
gae123
  • 8,589
  • 3
  • 35
  • 40
12

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}
Tomas Tomecek
  • 6,226
  • 3
  • 30
  • 26