How can I parse a YAML file from a Linux shell script?

Here is a bash-only parser that leverages sed and awk to parse simple yaml files: function parse_yaml { local prefix=$2 local s=”[[:space:]]*” w='[a-zA-Z0-9_]*’ fs=$(echo @|tr @ ‘\034’) sed -ne “s|^\($s\):|\1|” \ -e “s|^\($s\)\($w\)$s:$s[\”‘]\(.*\)[\”‘]$s\$|\1$fs\2$fs\3|p” \ -e “s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p” $1 | awk -F$fs ‘{ indent = length($1)/2; vname[indent] = $2; for (i in vname) {if (i > indent) … Read more

Is it .yaml or .yml?

The nature and even existence of file extensions is platform-dependent (some obscure platforms don’t even have them, remember) — in other systems they’re only conventional (UNIX and its ilk), while in still others they have definite semantics and in some cases specific limits on length or character content (Windows, etc.). Since the maintainers have asked … Read more

What is the difference between YAML and JSON?

Technically YAML is a superset of JSON. This means that, in theory at least, a YAML parser can understand JSON, but not necessarily the other way around. See the official specs, in the section entitled “YAML: Relation to JSON”. In general, there are certain things I like about YAML that are not available in JSON. … Read more

How can I parse a YAML file in Python

The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml: #!/usr/bin/env python import yaml with open(“example.yaml”, “r”) as stream: try: print(yaml.safe_load(stream)) except yaml.YAMLError as exc: print(exc) And that’s it. A plain yaml.load() function also exists, but yaml.safe_load() should always be preferred to avoid introducing … Read more

tech