Skip to content

Instantly share code, notes, and snippets.

@billroy
Created September 21, 2012 13:38
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save billroy/3761495 to your computer and use it in GitHub Desktop.
Save billroy/3761495 to your computer and use it in GitHub Desktop.
Read/write JSON object from file in python
import simplejson
import json
def put(data, filename):
try:
jsondata = simplejson.dumps(data, indent=4, skipkeys=True, sort_keys=True)
fd = open(filename, 'w')
fd.write(jsondata)
fd.close()
except:
print 'ERROR writing', filename
pass
def get(filename):
returndata = {}
try:
fd = open(filename, 'r')
text = fd.read()
fd.close()
returndata = json.read(text)
# Hm. this returns unicode keys...
#returndata = simplejson.loads(text)
except:
print 'COULD NOT LOAD:', filename
return returndata
if __name__ == '__main__':
o = get(sys.argv[1]);
if o:
put(o, sys.argv[1]);
@jamesbondo
Copy link

nice, thakns a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment