Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a YAML file to Python JSON object

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 
like image 448
ReKx Avatar asked Jun 13 '18 21:06

ReKx


People also ask

Can YAML be converted to JSON?

A YAML converter converts YAML configurations and documents into JSON configurations and files. It does not have any additional configuration options. Only one thing that you can alter is JSON's output. You have three choices: indent JSON using spaces or indent JSON using tabs and reduce JSON output.

How do I convert YAML to Python?

Adding YAML Support to Python Meaning, Python cannot read or interpret YAML documents by default. To add YAML support to Python, you have first to install the PyYAML module. To install the PyYAML module, you'll need to run the pip command, which is the package installer for Python.


2 Answers

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'}} 
like image 62
Brown Bear Avatar answered Sep 18 '22 11:09

Brown Bear


The PyYAML library is intended for this purpose

pip install pyyaml 
import yaml import json with open("example.yaml", 'r') as yaml_in, open("example.json", "w") as json_out:     yaml_object = yaml.safe_load(yaml_in) # yaml_object will be a list or a dict     json.dump(yaml_object, json_out) 

Notes: PyYAML only supports the pre-2009, YAML 1.1 specification.
ruamel.yaml is an option if YAML 1.2 is required.

pip install ruamel.yaml 
like image 36
Vemund Kvam Avatar answered Sep 16 '22 11:09

Vemund Kvam