You should pip install pyobjc
first.
Created
August 5, 2018 12:38
-
-
Save eigenhombre/e9ccfde71777362b1132bb1084bfd82b to your computer and use it in GitHub Desktop.
Exporting your Mac addressbook to JSON using Python
This file contains 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 | |
import AddressBook | |
import json | |
from Foundation import NSDictionary | |
from PyObjCTools import Conversion | |
FIELDS = {'first-name': AddressBook.kABFirstNameProperty, | |
'last-name': AddressBook.kABLastNameProperty, | |
'email': AddressBook.kABEmailProperty, | |
'address': AddressBook.kABAddressProperty, | |
'note': AddressBook.kABNoteProperty} | |
def generate_values(value): | |
for i in range(value.count()): | |
val = value.valueAtIndex_(i) | |
# C.f. https://clburlison.com/pyobjc-type-conversion/ : | |
yield Conversion.pythonCollectionFromPropertyList(val) | |
def lookup_and_convert(person, fieldname): | |
objcval = person.valueForProperty_(fieldname) | |
if isinstance(objcval, AddressBook.ABMultiValue): | |
return list(generate_values(objcval)) | |
elif objcval is None: | |
return None | |
else: | |
return objcval.encode('utf-8') | |
def main(): | |
book = AddressBook.ABAddressBook.sharedAddressBook() | |
people = [person for person in book.people()] | |
peopledicts = [dict((k, lookup_and_convert(p, v)) | |
for k, v in FIELDS.iteritems()) | |
for p in people] | |
print json.dumps(peopledicts, indent=4) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment