I use PyYAML to work with YAML files.
I wonder how I can properly check existence of some key? In the example below title
key is present only for list1. I want to process title value properly if it exists, and ignore if it is not there.
list1:
title: This is the title
active: True
list2:
active: False
There are many ways to check yaml file validation yamllint is one of the programs to check via command line In python, pyyaml package provides yaml validation with yamllint using python command, we can validate and print the validation logs to console IDE are a popular code editor to write and validate the code
This tool cannot be chained. Yaml validator tool What is a yaml validator? This YAML validator checks the syntax of YAML (Yet Another Markup Language) data. If there are mistakes, then it returns a detailed syntax error message that explains what happened. It also tells the position of error and displays the conflicting snippet.
yamllint is one of the programs to check via command line In python, pyyaml package provides yaml validation with yamllint using python command, we can validate and print the validation logs to console IDE are a popular code editor to write and validate the code
It is most often used in configuration files of servers and software applications. Clark Evans proposed the spec in 2001 as the result of an effort to simplify XML. According to his resume, at the time he conceived of YAML he was working with Python, which likely influenced the syntax of YAML as an indentation-based language.
Once you load this file with PyYaml, it will have a structure like this:
{
'list1': {
'title': "This is the title",
'active': True,
},
'list2: {
'active': False,
},
}
You can iterate it with:
for k, v in my_yaml.iteritems():
if 'title' in v:
# the title is present
else:
# it's not.
If you use yaml.load
, the result is a dictionary, so you can use in
to check if a key exists:
import yaml
str_ = """
list1:
title: This is the title
active: True
list2:
active: False
"""
dict_ = yaml.load(str_)
print dict_
print "title" in dict_["list1"] #> True
print "title" in dict_["list2"] #> False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With