Serializing YAML with PyYAML: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 27: Line 27:
=Customizing Output=
=Customizing Output=
==Customizing Output with <tt>dump()</tt> Parameters==
==Customizing Output with <tt>dump()</tt> Parameters==
<syntaxhighlight lang='python'>
# with the default flow style, the document is rendered in a non-indented manner
print (yaml.dump(data, default_flow_style=False))
</syntaxhighlight>
==Customizing Output with Representers==
==Customizing Output with Representers==


The general process of using a custom representer of a data type is described here: {{Internal|YAML_in_Python#Representer|YAML in Python &#124; Representer}}
The general process of using a custom representer of a data type is described here: {{Internal|YAML_in_Python#Representer|YAML in Python &#124; Representer}}

Revision as of 23:55, 7 December 2022

Internal

Overview

The process of serialization to YAML is rendering an in-memory data structure as a YAML-formatted string. The simplest sequence of statements that does that is:

import yaml

data = {
    'color': 'red',
    'size': 10,
    'parts': ['top', 'middle', 'bottom']
}

yaml_string = yaml.dump(data)

The YAML-formatted string will be:

color: red
parts:
- top
- middle
- bottom
size: 10

Customizing Output

Customizing Output with dump() Parameters

# with the default flow style, the document is rendered in a non-indented manner 
print (yaml.dump(data, default_flow_style=False))

Customizing Output with Representers

The general process of using a custom representer of a data type is described here:

YAML in Python | Representer