Created
April 25, 2018 12:28
-
-
Save tetrapus/952c6882e059625c653381b30be37b9e to your computer and use it in GitHub Desktop.
Simple python rison encoder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Simple RISON encoder. """ | |
import re | |
def encode(obj) -> str: | |
""" Encode an object to a RISON string. """ | |
# Objects | |
if isinstance(obj, dict): | |
return "({})".format( | |
",".join( | |
"{}:{}".format(encode(key), encode(value)) | |
for key, value in obj.items() | |
) | |
) | |
# Lists | |
if isinstance(obj, list): | |
return "!({})".format(",".join(encode(i) for i in obj)) | |
# Strings | |
if isinstance(obj, str): | |
if not obj: | |
return "''" | |
if re.match(r"^[^-0123456789!:(),*@$][^!:(),*@$]*$", obj): | |
return obj | |
obj = re.sub( | |
r"(['!])", | |
lambda match: ( | |
lambda char: '!' + char if char in "'!'" else char | |
)(match.group(1)), | |
obj | |
) | |
return "'%s'" % obj | |
# Literals | |
if obj is True: | |
return '!t' | |
if obj is False: | |
return '!f' | |
if obj is None: | |
return '!n' | |
# Numerics | |
return str(obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment