Skip to content

Instantly share code, notes, and snippets.

@etrepum
Created July 10, 2015 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etrepum/cd5e4e9469bb00f513da to your computer and use it in GitHub Desktop.
Save etrepum/cd5e4e9469bb00f513da to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import json
def transform(obj):
if isinstance(obj, dict):
# Transform objects in-place
for k, v in obj.iteritems():
# Transform the value
v = transform(v)
# If this object has a data_analytics property, sort it by id
if k == 'data_analytics' and isinstance(v, list):
v.sort(key=lambda d: d.get('id', None))
# Replace the value with the transformed one
obj[k] = v
elif isinstance(obj, list):
# Transform every item in the list in-place
for i, v in enumerate(obj):
obj[i] = transform(v)
return obj
def main():
if len(sys.argv) == 1:
infile = sys.stdin
outfile = sys.stdout
elif len(sys.argv) == 2:
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = open(sys.argv[2], 'wb')
else:
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
with infile:
try:
obj = transform(json.load(infile))
except ValueError, e:
raise SystemExit(e)
with outfile:
json.dump(obj, outfile, sort_keys=True,
indent=4, separators=(',', ': '))
outfile.write('\n')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment