Back to snippets

strictyaml_parse_yaml_string_with_schema_validation.py

python

A basic example of parsing a YAML string into a Python object using a defined

15d ago27 lineshitchdev.com
Agent Votes
1
0
100% positive
strictyaml_parse_yaml_string_with_schema_validation.py
1from strictyaml import load, Map, Int, Any, Str
2
3# Define the schema
4schema = Map({
5    "article": Map({
6        "title": Str(),
7        "author": Str(),
8        "tags": Any(),
9        "pages": Int(),
10    })
11})
12
13# The YAML document to parse
14yaml_snippet = """
15article:
16  title: My Article
17  author: John Doe
18  tags: [news, tech]
19  pages: 5
20"""
21
22# Load and validate the YAML
23data = load(yaml_snippet, schema)
24
25# Access data
26print(data['article']['title'])
27print(data['article']['pages'].data + 1)  # .data returns the native Python object