Allow LDAPObject classes (and sub-classes) to be serialized into a JSON string using:

 json.dumps(obj, default=ipalib.util.json_serialize)

Pavel
From 209162028b58ba8cc59e8c90409082eb8478a0dd Mon Sep 17 00:00:00 2001
From: Pavel Zuna <pz...@redhat.com>
Date: Mon, 9 Aug 2010 16:45:26 -0400
Subject: [PATCH 1/4] Make LDAPObject classes JSON serializable.

---
 ipalib/plugins/baseldap.py |   17 +++++++++++++++++
 ipalib/util.py             |    6 ++++++
 2 files changed, 23 insertions(+), 0 deletions(-)

diff --git a/ipalib/plugins/baseldap.py b/ipalib/plugins/baseldap.py
index 11fd18e..52f32e3 100644
--- a/ipalib/plugins/baseldap.py
+++ b/ipalib/plugins/baseldap.py
@@ -21,6 +21,7 @@ Base classes for LDAP plugins.
 """
 
 import re
+import json
 
 from ipalib import crud, errors, uuid
 from ipalib import Method, Object
@@ -29,6 +30,7 @@ from ipalib.base import NameSpace
 from ipalib.cli import to_cli, from_cli
 from ipalib import output
 from ipalib.text import _
+from ipalib.util import json_serialize
 
 
 def validate_add_attribute(ugettext, attr):
@@ -121,6 +123,21 @@ class LDAPObject(Object):
             }
         )
 
+    # list of attributes we want exported to JSON
+    json_friendly_attributes = (
+        'parent_object', 'container_dn', 'object_name', 'object_name_plural',
+        'object_class', 'object_class_config', 'default_attributes', 'label',
+        'hidden_attributes', 'uuid_attribute', 'attribute_members', 'name',
+        'takes_params',
+    )
+    def __json__(self):
+        json_dict = dict(
+            (a, getattr(self, a)) for a in self.json_friendly_attributes
+        )
+        json_dict['primary_key'] = self.primary_key.name
+        json_dict['methods'] = [m for m in self.methods]
+        return json_dict
+
 
 # Options used by create and update.
 _attr_options = (
diff --git a/ipalib/util.py b/ipalib/util.py
index 570d66e..ba111d4 100644
--- a/ipalib/util.py
+++ b/ipalib/util.py
@@ -31,6 +31,12 @@ from ipalib import errors
 from ipapython import dnsclient
 
 
+def json_serialize(obj):
+    if not callable(getattr(obj, '__json__', None)):
+        # raise TypeError('%r is not JSON serializable')
+        return ''
+    return obj.__json__()
+
 def get_current_principal():
     try:
         return 
unicode(krbV.default_context().default_ccache().principal().name)
-- 
1.7.1.1

_______________________________________________
Freeipa-devel mailing list
Freeipa-devel@redhat.com
https://www.redhat.com/mailman/listinfo/freeipa-devel

Reply via email to