Last active
August 21, 2021 18:02
-
-
Save ArjixWasTaken/f0ccf1ef638103dc67d5dd6f9c41f4e3 to your computer and use it in GitHub Desktop.
Converts any valid python data to its kotlin counterpart. (only works with native python data types)
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
def escape(string): | |
if ('"' in string): | |
return '"""{}"""'.format(string) | |
return '"{}"'.format(string) | |
def listToListOf(list_): | |
out = [] | |
for x in list_: | |
if type(x) in (int, float): | |
out.append(str(x)) | |
elif type(x) is str: | |
out.append(escape(x)) | |
elif type(x) in (list, tuple): | |
out.append(listToListOf(x)) | |
elif type(x) is dict: | |
out.append(dictToMapOf(x)) | |
return f'listOf({", ".join(out)})' | |
def dictToMapOf(obj): | |
out = [] | |
for key, value in obj.items(): | |
a = escape(key) if type(key) is str else str(key) | |
if type(value) in (int, float): | |
out.append((a, str(value))) | |
elif type(value) is str: | |
out.append((a, escape(value))) | |
elif type(value) in (list, tuple): | |
out.append((a, listToListOf(value))) | |
elif type(value) is dict: | |
out.append((a, dictToMapOf(value))) | |
map_ = [] | |
for key, value in out: | |
map_.append(f"""{key} to {value}""") | |
return f"mapOf({', '.join(map_)})" | |
def json2kotlin(data): | |
if type(data) in (list, tuple): | |
return listToListOf(data) | |
elif type(data) is dict: | |
return dictToMapOf(data) | |
elif type(data) is str: | |
return escape(data) | |
else: | |
return str(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment