Skip to content

Instantly share code, notes, and snippets.

@oberstet
Created April 5, 2017 08:21
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 oberstet/fa8b8e04b8d532912bd616d9db65101a to your computer and use it in GitHub Desktop.
Save oberstet/fa8b8e04b8d532912bd616d9db65101a to your computer and use it in GitHub Desktop.
import json
import base64
class _WAMPJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, six.binary_type):
return u'\x00' + base64.b64encode(obj).decode('ascii')
else:
return json.JSONEncoder.default(self, obj)
from json import scanner
from json.decoder import scanstring
def _parse_string(string, idx, strict):
s, idx = scanstring(string, idx, strict)
if s and s[0] == u'\x00':
s = base64.b64decode(s[1:])
return s, idx
class _WAMPJsonDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, *args, **kwargs)
self.parse_string = _parse_string
# we need to recreate the internal scan function ..
self.scan_once = scanner.py_make_scanner(self)
# .. and we have to explicitly use the Py version,
# not the C version, as the latter won't work
# self.scan_once = scanner.make_scanner(self)
def _loads(s):
return json.loads(s, cls=_WAMPJsonDecoder)
def _dumps(obj):
return json.dumps(obj,
separators=(',', ':'),
ensure_ascii=False,
sort_keys=False,
cls=_WAMPJsonEncoder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment