- def json_repr(obj):
- """Represent instance of a class as JSON.
- how to usage, e.g. : json_repr(your_object)
- Arguments:
- obj -- any object
- Return:
- String that reprent JSON-encoded object.
- """
- response.content_type = 'application/json'
- def serialize(obj):
- """Recursively walk object's hierarchy."""
- if isinstance(obj, (bool, int, long, float, basestring)):
- return obj
- elif isinstance(obj, dict):
- obj = obj.copy()
- for key in obj:
- obj[key] = serialize(obj[key])
- return obj
- elif isinstance(obj, list):
- return [serialize(item) for item in obj]
- elif isinstance(obj, tuple):
- return tuple(serialize([item for item in obj]))
- elif hasattr(obj, '__dict__'):
- return serialize(obj.__dict__)
- else:
- return repr(obj) # Don't know how to handle, convert to string
- return json.dumps(serialize(obj), encoding='utf-8')
- #该片段来自于http://www.codesnippet.cn/detail/0810201410536.html
来源: http://www.codesnippet.cn/detail/0810201410536.html