Skip to content

Instantly share code, notes, and snippets.

@nickgaya
Last active November 7, 2021 16:21
Show Gist options
  • Save nickgaya/645b612cf67831e19f7b48f183f8584a to your computer and use it in GitHub Desktop.
Save nickgaya/645b612cf67831e19f7b48f183f8584a to your computer and use it in GitHub Desktop.
Python script to convert plist data to JSON
#! /usr/bin/env python3
"""Read a plist from stdin and write its JSON equivalent to stdout."""
import base64
import datetime
import json
import plistlib
import sys
# UID type (Python 3.8+)
UID = getattr(plistlib, 'UID', None)
def plist_json_default(obj):
# Encode binary data as base64-encoded strings
if isinstance(obj, (bytes, bytearray)):
return base64.b64encode(obj).decode('ascii')
# Encode datetimes as ISO 8601 strings
# As with plistlib, datetimes are assumed to be in UTC
if isinstance(obj, datetime.datetime):
return '%04d-%02d-%02dT%02d:%02d:%02dZ' % (
obj.year, obj.month, obj.day,
obj.hour, obj.minute, obj.second
)
# Encode UIDs as integers
if UID and isinstance(obj, UID):
return obj.data
raise TypeError(f'Object of type {obj.__class__.__name__} '
'is not JSON serializable')
if __name__ == '__main__':
json.dump(plistlib.loads(sys.stdin.buffer.read()), sys.stdout,
separators=(',', ':'), default=plist_json_default)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment