Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a yaml string with python?

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

like image 831
gae123 Avatar asked May 05 '18 05:05

gae123


People also ask

How can I parse a YAML file in Python?

We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.

Does Python have a built in YAML parser?

However, Python lacks built-in support for the YAML data format, commonly used for configuration and serialization, despite clear similarities between the two languages. In this tutorial, you'll learn how to work with YAML in Python using the available third-party libraries, with a focus on PyYAML.


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 
like image 60
gae123 Avatar answered Oct 03 '22 00:10

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} 
like image 28
Tomas Tomecek Avatar answered Oct 03 '22 00:10

Tomas Tomecek