How can I load a YAML file and convert it to a Python JSON object?
My YAML file looks like this:
JavaScript
x
21
21
1
Section:
2
heading: Heading 1
3
font:
4
name: Times New Roman
5
size: 22
6
color_theme: ACCENT_2
7
8
SubSection:
9
heading: Heading 3
10
font:
11
name: Times New Roman
12
size: 15
13
color_theme: ACCENT_2
14
Paragraph:
15
font:
16
name: Times New Roman
17
size: 11
18
color_theme: ACCENT_2
19
Table:
20
style: MediumGrid3-Accent2
21
Advertisement
Answer
you can use PyYAML
JavaScript
1
2
1
pip install PyYAML
2
And in the ipython console:
JavaScript
1
39
39
1
In [1]: import yaml
2
3
In [2]: document = """Section:
4
heading: Heading 1 :
5
font: :
6
name: Times New Roman :
7
size: 22 :
8
color_theme: ACCENT_2 :
9
:
10
SubSection: :
11
heading: Heading 3 :
12
font: :
13
name: Times New Roman :
14
size: 15 :
15
color_theme: ACCENT_2 :
16
Paragraph: :
17
font: :
18
name: Times New Roman :
19
size: 11 :
20
color_theme: ACCENT_2 :
21
Table: :
22
style: MediumGrid3-Accent2""" :
23
:
24
25
In [3]: yaml.load(document)
26
Out[3]:
27
{'Paragraph': {'font': {'color_theme': 'ACCENT_2',
28
'name': 'Times New Roman',
29
'size': 11}},
30
'Section': {'font': {'color_theme': 'ACCENT_2',
31
'name': 'Times New Roman',
32
'size': 22},
33
'heading': 'Heading 1'},
34
'SubSection': {'font': {'color_theme': 'ACCENT_2',
35
'name': 'Times New Roman',
36
'size': 15},
37
'heading': 'Heading 3'},
38
'Table': {'style': 'MediumGrid3-Accent2'}}
39