Improve serialization to JSON.

- Make it recursive.
- Make Param classes serializable.
- Take python native data types into account.
This commit is contained in:
Pavel Zuna 2010-08-10 16:40:00 -04:00 committed by Rob Crittenden
parent 58fd1199f6
commit f15758dbea
3 changed files with 27 additions and 2 deletions

View File

@ -852,6 +852,20 @@ class Param(ReadOnly):
pass
return self.default
def __json__(self):
json_dict = {}
for (a, k, d) in self.kwargs:
if k in (callable, DefaultFrom):
continue
elif isinstance(getattr(self, a), frozenset):
json_dict[a] = [k for k in getattr(self, a, [])]
else:
json_dict[a] = getattr(self, a, '')
json_dict['class'] = self.__class__.__name__
json_dict['name'] = self.name
json_dict['type'] = self.type.__name__
return json_dict
class Bool(Param):
"""

View File

@ -137,7 +137,8 @@ class LDAPObject(Object):
json_dict = dict(
(a, getattr(self, a)) for a in self.json_friendly_attributes
)
json_dict['primary_key'] = self.primary_key.name
if self.primary_key:
json_dict['primary_key'] = self.primary_key.name
json_dict['methods'] = [m for m in self.methods]
return json_dict

View File

@ -27,15 +27,25 @@ import logging
import time
import krbV
import socket
from types import NoneType
from ipalib import errors
from ipapython import dnsclient
def json_serialize(obj):
if isinstance(obj, (list, tuple)):
return [json_serialize(o) for o in obj]
if isinstance(obj, dict):
return dict((k, json_serialize(v)) for (k, v) in obj.iteritems())
if isinstance(obj, (bool, float, int, unicode, NoneType)):
return obj
if isinstance(obj, str):
return obj.decode('utf-8')
if not callable(getattr(obj, '__json__', None)):
# raise TypeError('%r is not JSON serializable')
return ''
return obj.__json__()
return json_serialize(obj.__json__())
def get_current_principal():
try: