Source code for jsonrpc.jsonutil

# $Id: jsonutil.py,v 1.2 2011/05/26 19:34:19 edwlan Exp $
"""
This module is primarily a wrapper around simplejson in order to make
it behave like demjson

- If an object being encoded has a 'json_equivalent' attribute, that will be called to get a (more)
	serializable object

- if it has an 'items' method, it will be called
	- if it defines both items and iteritems, the second will be used)

- if it is iterable, it will be made into a list

- otherwise 'str' will be called on the object, and that result will be used
"""
__all__ = ['encode', 'decode']

import functools

try:
	import json
except ImportError:
	import simplejson as json


def dict_encode(obj):
	items = getattr(obj, 'iteritems', obj.items)
	return dict( (encode_(k),encode_(v)) for k,v in items() )

def list_encode(obj):
	return list(encode_(i) for i in obj)

def safe_encode(obj):
	'''Always return something, even if it is useless for serialization'''
	try: json.dumps(obj)
	except TypeError: obj = str(obj)
	return obj

def encode_(obj, **kw):
	obj = getattr(obj, 'json_equivalent', lambda: obj)()
	func = lambda x: x
	if hasattr(obj, 'items'):
		func = dict_encode
	elif hasattr(obj, '__iter__'):
		func = list_encode
	else:
		func = safe_encode
	return func(obj)


encode = functools.partial(json.dumps, default=encode_)
decode = json.loads

__version__ = "$Revision: 1.2 $".split(":")[1][:-1].strip()