I see an API and many examples on how to parse a yaml file but what about a string?
2 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 3 Comments
Nikhil Talreja
When I use this method, the type of
dct is still stringTomas Tomecek
you should use
yaml.safe_load for untrusted inputsJohannes
if you need to install the library, be aware that it is
pip install pyyaml but import yaml
yaml.load/safe_loadis 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 withload/loads. Hard to try using a function that doesn't exist and there's nothing wrong with ... just asking a question.