将YAML文件转换为Python JSON对象
如何加载YAML文件并将其转换为Python JSON对象?
我的YAML文件如下所示:
Section: heading: Heading 1
font:
name: Times New Roman
size: 22
color_theme: ACCENT_2
SubSection:
heading: Heading 3
font:
name: Times New Roman
size: 15
color_theme: ACCENT_2
Paragraph:
font:
name: Times New Roman
size: 11
color_theme: ACCENT_2
Table:
style: MediumGrid3-Accent2
回答:
你可以使用PyYAML
pip install PyYAML
并在ipython控制台中:
In [1]: import yamlIn [2]: document = """Section:
...: heading: Heading 1
...: font:
...: name: Times New Roman
...: size: 22
...: color_theme: ACCENT_2
...:
...: SubSection:
...: heading: Heading 3
...: font:
...: name: Times New Roman
...: size: 15
...: color_theme: ACCENT_2
...: Paragraph:
...: font:
...: name: Times New Roman
...: size: 11
...: color_theme: ACCENT_2
...: Table:
...: style: MediumGrid3-Accent2"""
...:
In [3]: yaml.load(document)
Out[3]:
{'Paragraph': {'font': {'color_theme': 'ACCENT_2',
'name': 'Times New Roman',
'size': 11}},
'Section': {'font': {'color_theme': 'ACCENT_2',
'name': 'Times New Roman',
'size': 22},
'heading': 'Heading 1'},
'SubSection': {'font': {'color_theme': 'ACCENT_2',
'name': 'Times New Roman',
'size': 15},
'heading': 'Heading 3'},
'Table': {'style': 'MediumGrid3-Accent2'}}
以上是 将YAML文件转换为Python JSON对象 的全部内容, 来源链接: utcz.com/qa/418226.html