Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Again with strategies (now for lists) solution in Clear category for YAML. List and Comments by swagg010164
import re
def to_value(value):
strategy = {lambda x: x.lower() == "true": True,
lambda x: x.lower() == "false": False,
lambda x: not x or x == 'null': None,
lambda x: x.startswith('"') and x.endswith('"'): value[1:-1],
lambda x: 1: value.strip()}
try:
return int(value)
except ValueError:
for func in strategy:
if func(value):
return strategy[func]
def yaml_from_array(s):
return [to_value(bytes(b[2:], "utf-8").decode('unicode_escape')) for b in s]
def check_array(s):
s = [elem for i in s for elem in i if elem.startswith('-')]
s = [re.sub(r'("(?:[^"]+|(?<=\\)")*")|#[^\n]*', lambda m: m.group(1) or '', k) for k in s]
if s:
return s
return []
def yaml(a):
s = [[i.strip() for i in k.split(':')] for k in a.split('\n') if k != '']
if check_array(s):
s = check_array(s)
return yaml_from_array(s)
return {a.strip(): to_value(bytes(b, "utf-8").decode('unicode_escape')
) for a, b in s}
Nov. 10, 2019