Skip to content
Advertisement

Converting a YAML file to JSON object in Python

How can I load a YAML file and convert it to a Python JSON object?

My YAML file looks like this:

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

Advertisement

Answer

you can use PyYAML

pip install PyYAML

And in the ipython console:

In [1]: import yaml

In [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'}}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement