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?
Try transforming the CaseInsensitiveDict
to a plain old dict
, like so:
json.dump(dict(data), file)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With