15

I am working on what I assumed would be a simple problem but it has really confused. I am making an AD query in Python using the ldap3 module. This query is returning the data as generator of python dictionaries. When I run the type() command against the data it confirms that it is a dictionary.

I need to convert this into JSON so that I can write it to a log file. First, I tried json.dump(data, file) but when I do that I receive this error: TypeError: Object of type 'CaseInsensitiveDict' is not JSON serializable

If I try and convert the dictionary to a string first the data is written with quotes and inner fields are left with single quotes so it isn't true JSON - it comes out looking like this: "{'key': 'value'}"

Here is what I have:

with open(outfile, 'w') as outfile:
    for entry in entry_generator: # Entry is equal to a dictionary of AD attributes
        json.dump(entry, outfile) # I have also tried json.dump(str(entry), outfile) etc

I have been searching the interwebs and I see a lot about this issue with the requests module but nothing that seems to fix my situation.

With the ldap3 module there is a method entry_to_json() which I used in other scripts. It doesn't seem to work here because of the generator, if anyone knows how to make that work again it could solve my problem. Thoughts?

Joe
  • 2,641
  • 5
  • 22
  • 43

1 Answers1

26

Try transforming the CaseInsensitiveDict to a plain old dict, like so:

json.dump(dict(data), file)
GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16
  • 2
    I was actually just trying this exact solution right now. And it is failing - There is only one nested dict so hopefully you're right and that is the issue. I am going crazy with this problem – Joe Mar 17 '20 at 13:07
  • -- WOW THANKYOU - I couldn't figure out why I was continually failing, but you were right it was because of the nested dict. What a pain that was, thank you again!!! – Joe Mar 17 '20 at 13:11
  • I'm glad to help. I just tried transforming a nested CaseInsensitiveDict (requests.structures.CaseInsensitiveDict), and to my surprise `dict()` transformed the nested one, too. Neat. – GordonAitchJay Mar 17 '20 at 13:19
  • Major! This is such a clean solution! – young_souvlaki Nov 16 '20 at 21:05