Skip to content

Instantly share code, notes, and snippets.

@tabatkins
Last active December 20, 2015 13:09
Show Gist options
  • Save tabatkins/6136662 to your computer and use it in GitHub Desktop.
Save tabatkins/6136662 to your computer and use it in GitHub Desktop.
Tiny library/command-line-program for converting between json and plist formats. I use it for editing SublimeText setting files.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import plistlib
import json
import StringIO
# Takes as input a string of either JSON or Plist.
# Returns the opposite, assuming no errors.
def convert(input):
try:
inputType = "json"
data = json.loads(input)
except Exception, e:
try:
inputType = "plist"
data = plistlib.readPlist(StringIO.StringIO(input))
except:
print("FATAL ERROR: Couldn't parse input as either JSON or Plist.")
raise
if inputType == "json":
output = StringIO.StringIO()
plistlib.writePlist(data, output)
return output.getvalue()
return json.dumps(data, indent=2)
if __name__ == "__main__":
import optparse
import sys
optparser = optparse.OptionParser("usage: %prog [options] inputFile")
optparser.add_option("-i", "--in", dest="inputFile",
help="Path to the source file. [default: standard input]")
optparser.add_option("-o", "--out", dest="outputFile",
help="Path to the output file. [default: standard output]")
optparser.add_option("-r", "--replace", dest="replace", action="store_true",
help="Just replaces the input file with the output. Must specify an input as well.")
(options, posargs) = optparser.parse_args()
if len(posargs) == 1:
options.inputFile = posargs[0]
elif len(posargs) == 0:
inputFile = None
else:
optparser.error("One or zero arguments, please.")
if options.inputFile and options.replace:
options.outputFile = options.inputFile
if options.inputFile:
with open(options.inputFile, 'r') as input:
output = convert(input.read())
else:
input = sys.stdin.read()
output = convert(input)
if options.outputFile:
with open(options.outputFile, 'w') as outputF:
outputF.write(output)
else:
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment