Pretty-Print JSON Data to a File using Python Pretty-Print JSON Data to a File using Python python python

Pretty-Print JSON Data to a File using Python


You should use the optional argument indent.

header, output = client.request(twitterRequest, method="GET", body=None,                            headers=None, force_auth_header=True)# now write output to a filetwitterDataFile = open("twitterData.json", "w")# magic happens here to make it pretty-printedtwitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))twitterDataFile.close()


You can parse the JSON, then output it again with indents like this:

import jsonmydata = json.loads(output)print json.dumps(mydata, indent=4)

See http://docs.python.org/library/json.html for more info.


import jsonwith open("twitterdata.json", "w") as twitter_data_file:    json.dump(output, twitter_data_file, indent=4, sort_keys=True)

You don't need json.dumps() if you don't want to parse the string later, just simply use json.dump(). It's faster too.