Storing JSON data to disk
Calls to the API can be expensive in terms of bandwidth and the rate limits that service providers place on their API. While Twitter is quite generous about these limits, other services are not. Regardless, it is good practice to save the retrieved JSON structures to disk for later use.
Getting ready
For this recipe, you will need previously retrieved data, preferably from the previous recipes.
How to do it...
The following steps walk us through saving the JSON data to disk and then loading it back into the Python interpreter's memory:
- First, we must import the
json
package and create two helper functions:
In [31]: import json
...: def save_json(filename, data):
...: with open(filename, 'wb') as outfile:
...: json.dump(data, outfile)
In [32]: def load_json(filename):
...: with open(filename) as infile:
...: data = json.load(infile)
...: return data
- At the Python prompt, let's test our functions by saving our friends' JSON-based Twitter...