66

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

3
  • 1
    FYI YAML is not safe. It is susceptible to vulnerabilities that allows the user to execute code on your servers youtube.com/watch?v=LrW-HSHP0ws Commented May 5, 2018 at 5: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. Commented May 5, 2018 at 6:02
  • 6
    @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. Commented Aug 12, 2020 at 7:03

2 Answers 2

96

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 
Sign up to request clarification or add additional context in comments.

3 Comments

When I use this method, the type of dct is still string
you should use yaml.safe_load for untrusted inputs
if you need to install the library, be aware that it is pip install pyyaml but import yaml
15

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} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.