Created
August 6, 2021 12:29
-
-
Save karlkfi/e696cedb055e774f748cf7887b6468ac to your computer and use it in GitHub Desktop.
json encode in starlark
This file contains 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
# In a Starlark context that doesn't support json or recursion, | |
# you might become desperate enough to do something crazy like this... | |
def quoteIfString(obj): | |
if type(obj) == "string": | |
return '"' + obj + '"' | |
else: | |
return obj | |
def jsonEncode(obj): | |
stack = [obj] | |
json = "" | |
for i in range(10000): | |
if i >= len(stack): | |
# empty stack! | |
break | |
item = stack[i] | |
if type(item) == "list": | |
x = [] | |
x.append("[") | |
for j, elem in enumerate(item): | |
if j > 0: | |
x.append(",") | |
x.append(quoteIfString(elem)) | |
x.append("]") | |
stack = stack[:i+1] + x + stack[i+1:] | |
continue | |
if type(item) == "dict": | |
x = [] | |
x.append("{") | |
for j, elem in enumerate(item.items()): | |
if j > 0: | |
x.append(",") | |
x.append(quoteIfString(elem[0])) | |
x.append(":") | |
x.append(quoteIfString(elem[1])) | |
x.append("}") | |
stack = stack[:i+1] + x + stack[i+1:] | |
continue | |
t = type(item) | |
if t == "string": | |
json += item # already quoted | |
elif t == "bool": | |
json += "true" if item else "false" | |
elif t == "int": | |
json += str(item) | |
elif t == None: | |
json += "null" | |
else: | |
return fail("Error: unsupported json type: " + t) | |
return json | |
# P.S. This code is embarasingly bad. Please don't make me code it again in an interview. | |
# P.P.S. Yes, it works... for the limitted set of inputs I needed it to... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment