json2msgpack.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python
  2. __doc__ = '''
  3. Convert a json file to msgpack.
  4. If fed only an input file the converted will write out a .pack file
  5. of the same base name in the same directory
  6. $ json2msgpack.py -i foo.json
  7. foo.json > foo.pack
  8. Specify an output file path
  9. $ json2msgpack.py -i foo.json -o /bar/tmp/bar.pack
  10. foo.json > /bar/tmp/bar.pack
  11. Dependencies:
  12. https://github.com/msgpack/msgpack-python
  13. '''
  14. import os
  15. import sys
  16. import json
  17. import argparse
  18. sys.path.append(os.path.dirname(os.path.realpath(__file__)))
  19. import msgpack
  20. EXT = '.pack'
  21. def main():
  22. parser = argparse.ArgumentParser()
  23. parser.add_argument('-i', '--infile', required=True,
  24. help='Input json file to convert to msgpack')
  25. parser.add_argument('-o', '--outfile',
  26. help=('Optional output. If not specified the .pack file '\
  27. 'will write to the same director as the input file.'))
  28. args = parser.parse_args()
  29. convert(args.infile, args.outfile)
  30. def convert(infile, outfile):
  31. if not outfile:
  32. ext = infile.split('.')[-1]
  33. outfile = '%s%s' % (infile[:-len(ext)-1], EXT)
  34. print('%s > %s' % (infile, outfile))
  35. print('reading in JSON')
  36. with open(infile) as op:
  37. data = json.load(op)
  38. print('writing to msgpack')
  39. with open(outfile, 'wb') as op:
  40. msgpack.dump(data, op)
  41. if __name__ == '__main__':
  42. main()