Created
April 15, 2009 21:48
-
-
Save jcsalterego/96044 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # | |
| # Converts standard LDIF to a list of dicts | |
| # | |
| import sys | |
| from base64 import b64decode | |
| from pprint import pprint | |
| SOURCE = "source.ldf" | |
| def main(): | |
| objs = ldf_to_dict(file(SOURCE)) | |
| pprint(objs) | |
| return 0 | |
| def ldf_to_dict(fh): | |
| f = fh.read() | |
| fh.close() | |
| # sanitize file; join multiple lines and strip \r | |
| f = f.replace("\r", "").replace("\n ", "") | |
| item_objs = [] | |
| items = f.split("\n\n") | |
| for item in items: | |
| item_obj = {} | |
| for line in item.split("\n"): | |
| if not line: | |
| continue | |
| key, value = line.split(": ", 1) | |
| if key[-1] == ":": | |
| # double colon indicates base64 | |
| value = b64decode(value) | |
| key = key[:-1] | |
| if key not in item_obj: | |
| item_obj[key] = value | |
| elif type(item_obj[key]) == type([]): | |
| item_obj[key].append(value) | |
| else: | |
| item_obj[key] = [item_obj[key], value] | |
| item_objs.append(item_obj) | |
| return item_objs | |
| if __name__ == "__main__": | |
| sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment