Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
All in one dict comprehesion :) solution in Clear category for YAML. More Types by Sebdidier
def yaml(a):
return {attr.split(':')[0]:
None if len(attr.split(': ')) < 2
else None if attr.split(': ')[1].lower() == 'null'
else False if attr.split(': ')[1].lower() == 'false'
else True if attr.split(': ')[1].lower() == 'true'
else int(attr.split(': ')[1]) if attr.split(': ')[1].isdigit()
else attr.split(': ')[1].replace('"', '').replace('\\', '"').strip()
for attr in a.splitlines() if attr}
if __name__ == '__main__':
print("Example:")
print(yaml('name: Alex\nage: 12'))
# These "asserts" are used for self-checking and not for an auto-testing
assert yaml('name: Alex\nage: 12') == {'age': 12, 'name': 'Alex'}
assert yaml('name: Alex Fox\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex Fox'}
assert yaml('name: "Alex Fox"\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex Fox'}
assert yaml('name: "Alex \\"Fox\\""\n'
'age: 12\n'
'\n'
'class: 12b') == {'age': 12,
'class': '12b',
'name': 'Alex "Fox"'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'alive: false') == {'alive': False,
'children': 6,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding:') == {'children': 6,
'coding': None,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding: null') == {'children': 6,
'coding': None,
'name': 'Bob Dylan'}
assert yaml('name: "Bob Dylan"\n'
'children: 6\n'
'coding: "null" ') == {'children': 6,
'coding': 'null',
'name': 'Bob Dylan'}
print("Coding complete? Click 'Check' to earn cool rewards!")
Jan. 12, 2021