Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
recursion solution in Clear category for YAML. Complex Structure by kdim
def convert(value): # return converted
transform = {'"null"': 'null', '': None, 'null': None, # value
'true': True, 'false': False} #
if value in transform:
return transform[value]
value = value.replace('\\', '').replace('\"', '"')
if value[0] == value[-1] == '"':
value = value[1:-1]
return int(value) if value.isdigit() else value
def remove_comment(text): # remove comment
quoted, data = False, '' # from line
for char in text: #
if char == '"':
quoted = not quoted
if char == '#' and not quoted:
return data
data += char
return data
def get_yaml(text): # recursively get yaml
index = lambda x: len(x) - len(x.lstrip()) # block indent
ix = index(text[0]) #
(delimeter, result) = ('-', []) if '-' in text[0] else (':', {}) # type of block
while text: # let's go through the block
line = text.pop(0) # get line
key, value = line.split(delimeter) # get key and value
key, value = key.strip(), convert(value.strip()) # if list then key = ''
if line.strip()[-1] == delimeter and text and index(text[0]) != ix:
subtext = [] # if find sub-block, go recursively through one
while text and index(text[0]) != ix: # get subblock text
subtext.append(text.pop(0)) #
value = get_yaml(subtext) # recursion
if delimeter == ':': #
result.update({key: value}) # add value to result
else: #
result.append(value) #
return result #
def yaml(a):
value = [remove_comment(line) for line in a.split('\n') if line and line[0] != '#']
return get_yaml(value)
March 2, 2021
Comments: