简体   繁体   English

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

[英]How do I parse a yaml string with python?

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

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

You don't need to wrap the string in StringIO, the safe_load method accepts strings:您不需要将字符串包装在 StringIO 中, safe_load方法接受字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM