Some intro text here.
As we're writing the encoder, we will write some basic tests to see if it's working as intended. We won't be testing all the edge cases extensively, but the tests should still serve as a basic sanity check.
In order to test against a known implementation; we can encode the value, decode it with Python's built-in json module and compare the results.
def check_encode(value):
import json
return json.loads(encode(value)) == value
def encode(value):
In JSON encoding, True encodes to true
and False encodes to false
. We can
perform the encoding using a simple if statement.
if isinstance(value, bool):
if value:
return "true"
else:
return "false"
In order to encode numbers, we can use the str
function in Python that can
convert any type into a string. While the other -more complicated- types will
require extra care, for numbers this should be good enough.
elif isinstance(value, int) or isinstance(value, float):
return str(value)
This is probably the easiest value to encode.
elif value is None:
return "null"
elif isinstance(value, str):
result = ''
for c in value:
if c == '"':
result += r'\"'
elif c == '\n':
result += r'\n'
else:
result += c
return f'"{result}"'
elif isinstance(value, list):
result = ''
for elem in value:
if result != '':
result += ','
result += encode(elem)
return f'[{result}]'
elif isinstance(value, dict):
result = ''
for key in value:
if result != '':
result += ','
result_key = encode(str(key))
result += f'{result_key}: {encode(value[key])}'
return '{' + result + '}'
assert check_encode(1234)
assert check_encode(-1234)
assert check_encode(0)
assert check_encode(00)
assert check_encode(0.112233)
assert check_encode(1e3)
assert check_encode(True)
assert check_encode(False)
assert check_encode(None)
assert check_encode('hello')
assert check_encode('Hello "world"')
assert check_encode([])
assert check_encode([1])
assert check_encode([1,2,3])
assert check_encode({'name': 'Leo', 'health': 100.0})