Skip to content

Instantly share code, notes, and snippets.

@gkbrk
Created December 3, 2019 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkbrk/9fb1877981b5691446d888a8b341c6a4 to your computer and use it in GitHub Desktop.
Save gkbrk/9fb1877981b5691446d888a8b341c6a4 to your computer and use it in GitHub Desktop.
JSON Encoder - unbird example
def check_encode(value):
import json
return json.loads(encode(value)) == value
def encode(value):
if isinstance(value, bool):
if value:
return "true"
else:
return "false"
elif isinstance(value, int) or isinstance(value, float):
return str(value)
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})
Writing a simple JSON encoder in Python
==========================================
# Intro
Some intro text here.
# Testing
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):
# Encoding booleans
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"
# Encoding numbers
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)
# Encoding null
This is probably the easiest value to encode.
> elif value is None:
> return "null"
# Encoding strings
> 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}"'
# Encoding lists
> elif isinstance(value, list):
> result = ''
> for elem in value:
> if result != '':
> result += ','
> result += encode(elem)
> return f'[{result}]'
# Encoding dicts
> 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 + '}'
# Testing
> 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})

Writing a simple JSON encoder in Python

Intro

Some intro text here.

Testing

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):

Encoding booleans

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"

Encoding numbers

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)

Encoding null

This is probably the easiest value to encode.

   elif value is None:
       return "null"

Encoding strings

   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}"'

Encoding lists

   elif isinstance(value, list):
     result = ''
     for elem in value:
       if result != '':
         result += ','
       result += encode(elem)
     return f'[{result}]'

Encoding dicts

   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 + '}'

Testing

 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})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment