如何使用 python 解析 yaml 字符串?

How do I parse a yaml string with python?

我看到一个 API 和许多关于如何解析 yaml 文件的示例,但是字符串呢?

这是迄今为止我见过的最好的示例演示方法:

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

你不需要在 StringIO 中包装字符串,safe_load 方法接受字符串:

In [1]: yaml.safe_load("{1: 2}")           
Out[1]: {1: 2}