Skip to content

Instantly share code, notes, and snippets.

@FelixWolf
Last active December 2, 2025 07:26
Show Gist options
  • Select an option

  • Save FelixWolf/9d2c7179f3c5e7c7bdf374a37074e3cd to your computer and use it in GitHub Desktop.

Select an option

Save FelixWolf/9d2c7179f3c5e7c7bdf374a37074e3cd to your computer and use it in GitHub Desktop.
lljson compatible python library
"""
Author: Kyler "Félix" Eastridge
License: CC0
No Copyright
The person who associated a work with this deed has dedicated the work to
the public domain by waiving all of his or her rights to the work worldwide
under copyright law, including all related and neighboring rights, to the
extent allowed by law.
You can copy, modify, distribute and perform the work, even for commercial
purposes, all without asking permission. See Other Information below.
Other Information
In no way are the patent or trademark rights of any person affected by CC0,
nor are the rights that other persons may have in the work or in how the
work is used, such as publicity or privacy rights.
Unless expressly stated otherwise, the person who associated a work with
this deed makes no warranties about the work, and disclaims liability for
all uses of the work, to the fullest extent permitted by applicable law.
When using or citing the work, you should not imply endorsement by the
author or the affirmer.
"""
__all__ = ["slencode", "sldecode"]
import json
import uuid
import base64
class Vector:
def __init__(self, x,y,z):
self.x, self.y, self.z = x, y, z
def __repr__(self):
return "<{}, {}, {}>".format(self.x, self.y, self.z)
class Rotation:
def __init__(self, x,y,z,s):
self.x, self.y, self.z, self.s = x, y, z, s
def __repr__(self):
return "<{}, {}, {}, {}>".format(self.x, self.y, self.z, self.s)
defaultTypes = {
"vector": Vector,
"rotation": Rotation
}
def encodeType(value, tight, types):
if type(value) == str:
if value.startswith("!"):
return "!{}".format(value)
return value
elif type(value) == bool:
if value:
return "!b1"
return "!b0"
elif type(value) == float or type(value) == int:
return "!f{}".format(value)
elif type(value) == bytes:
raise NotImplemented("Bytes not implemented yet!")
elif type(value) == uuid.UUID:
if tight:
return "!u{}".format(base64.b64encode(value.bytes)[:-2].decode())
return "!u{}".format(str(value))
elif type(value) == types["vector"]:
if tight:
return "!v{},{},{}".format(
"" if value.x == 0 else value.x,
"" if value.y == 0 else value.y,
"" if value.z == 0 else value.z,
)
return "!v<{},{},{}>".format(value.x, value.y, value.z)
elif type(value) == types["rotation"]:
if tight:
return "!q{},{},{},{}".format(
"" if value.x == 0 else value.x,
"" if value.y == 0 else value.y,
"" if value.z == 0 else value.z,
"" if value.s == 0 else value.s,
)
return "!q<{},{},{},{}>".format(value.x, value.y, value.z, value.s)
elif type(value) == list:
result = [None] * len(value) # Pre-allocate
for i, v in enumerate(value):
result[i] = encodeType(v, tight, types)
return result
elif type(value) == dict:
result = {}
for k,v in value.items():
result[encodeType(k, tight, types)] = encodeType(v, tight, types)
return result
def decodeType(value, types):
if type(value) == str:
if value.startswith("!") and len(value) > 1:
tag, entry = value[1], value[2:]
if tag == "!":
return value[1:]
elif tag == "b":
if entry == "1":
return True
elif entry == "0":
return False
else:
raise ValueError("malformed tagged boolean: {}".format(value))
elif tag == "f":
return float(entry)
elif tag == "u":
if len(entry) == 0:
return uuid.UUID("00000000-0000-0000-0000-000000000000")
elif len(entry) == 36:
return uuid.UUID(entry)
elif len(entry) == 22:
return uuid.UUID(bytes=base64.b64decode(entry+"=="))
else:
raise ValueError("invalid UUID format for JSON encoding")
elif tag == "v":
if entry.count(",") < 2:
raise ValueError("malformed tagged vector: {}".format(value))
x, y, z = entry.split(",",3)
return types["vector"](float(x or "0"),float(y or "0"),float(z or "0"))
elif tag == "q":
if entry.count(",") < 3:
raise ValueError("malformed tagged rotation: {}".format(value))
x, y, z, s = entry.split(",",3)
return types["rotation"](float(x or "0"),float(y or "0"),float(z or "0"),float(s or "0"))
else:
raise ValueError("unknown tag '!{}' in string: {}".format(tag, value))
else:
return value
elif type(value) == list:
result = [None] * len(value) # Pre-allocate
for i, v in enumerate(value):
result[i] = decodeType(v, types)
return result
elif type(value) == dict:
result = {}
for k,v in value.items():
result[decodeType(k, types)] = decodeType(v, types)
return result
def slencode(obj, tight = False, types = None):
if types == None:
types = defaultTypes
return json.dumps(encodeType(obj, tight, types))
def sldecode(encoded, types = None):
if types == None:
types = defaultTypes
return decodeType(json.loads(encoded), types)
if __name__ == "__main__":
print(
sldecode(slencode({
1: "one",
100: "hundred",
True: "true",
False: "false",
Vector(1, 0, 0): "a_vec",
uuid.uuid4(): "my_uuid"
}, True))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment