noirello / bonsai

Simple Python 3 module for LDAP, using libldap2 and winldap C libraries.
MIT License
116 stars 32 forks source link

How to convert search return value to JSON? #79

Closed kingluo closed 1 year ago

kingluo commented 1 year ago

@noirello For example, how to convert such a search result into a JSON array/object without constructing a new list/dict and copying fields one by one?

[{'dn': <LDAPDN CN=chuck,DC=bonsai,DC=test>,
  'memberOf': ['CN=foobar,DC=bonsai,DC=test'],
  'sAMAccountName': ['chuck']}]

LDAPEntry and LDAPDN is not JSON serializable.

noirello commented 1 year ago

There's no easy way. You have to either replace the LDAPDN classes with their str representation in the entry, or create a custom JSONEncoder for LDAPDN. I think the LDAPEntry and LDAPValueList objects should be JSON serializable, they're inherited from dict and list respectively.

kingluo commented 1 year ago

@noirello Thanks for your help. Now I encapsulate bonsai in OpenResty Lua library: https://github.com/kingluo/lua-resty-ffi-ldap/blob/main/resty/ffi/ldap.py

If you have time, please have a look. Any suggestions are welcome! Thank you!

noirello commented 1 year ago

I think this is a shorter and maybe a little bit faster approach:

for ent in res:
    item = dict(ent)
    item["dn"] = str(item["dn"])
    ents.append(item)

Then this here: https://github.com/kingluo/lua-resty-ffi-ldap/blob/4f0f625e69dba2d676787641db29b6918b2d778f/resty/ffi/ldap.py#L111-L118

Other then that, I have no notes. That's a very compelling language mix, you've got there. 😃

kingluo commented 1 year ago

@noirello It's more pythonic! Thanks for your suggestion!