Skip to content

Instantly share code, notes, and snippets.

@NegativeMjark
Last active August 29, 2015 14:14
Show Gist options
  • Save NegativeMjark/8e3ac3b75ed0b2ca5819 to your computer and use it in GitHub Desktop.
Save NegativeMjark/8e3ac3b75ed0b2ca5819 to your computer and use it in GitHub Desktop.
Trivial JSON encoder
OBJECT_CONSTANTS = {
True: '":true,"',
False: '":false,"',
None: '":null,"',
}
ARRAY_CONSTANTS = {
True: 'true,',
False: 'false,',
None: 'null,',
}
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
for i in range(0x20):
ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
def replace_escape(match):
return ESCAPE_DCT[match.group(0)]
def encode_json_object(json_object, res):
items = sorted(json_object.items())
if items:
sep = b'{"'
for k_str, v_obj in items:
k_type = type(k_str)
res.append(sep)
res.append(ESCAPE.sub(replace_escape, k_str.encode("UTF-8")))
v_type = type(v_obj)
if v_type is unicode or v_type is bytes:
res.append(b'":"')
res.append(ESCAPE.sub(replace_escape, v_obj.encode("UTF-8")))
sep = b'","'
elif v_type is int or v_type is long:
res.append(b'":')
res.append(bytes(v_obj))
sep = b',"'
elif v_type is dict or v_type is frozendict:
res.append(b'":')
encode_json_object(v_obj, res)
sep = b',"'
elif v_type is list or v_type is tuple:
res.append(b'":')
encode_json_array(v_obj, res)
sep = b',"'
else:
sep = OBJECT_CONSTANTS[v_obj]
res.append(sep[:-2] + b'}')
else:
res.append(b'{}')
def encode_json_array(json_array, res):
if json_array:
sep = b'{"'
for v_obj in json_array:
res.append(sep)
v_type = type(v_obj)
if v_type is unicode or v_type is bytes:
res.append(b'"')
res.append(ESCAPE.sub(replace_escape, v_obj.encode("UTF-8")))
sep = b'",'
elif v_type is int or v_type is long:
res.append(bytes(v_obj))
sep = b','
elif v_type is dict or v_type is frozendict:
encode_json_object(v_obj, res)
sep = b','
elif v_type is list or v_type is tuple:
encode_json_array(v_obj, res)
sep = b','
else:
sep = ARRAY_CONSTANTS[v_obj]
res.append(sep[:-1] + b']')
else:
res.append(b'{}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment