Python Tip: Dump JSON to and From a File

avatar

Python

Python is such a beautiful swiss army knife of a language. In this article, I want to share an easy but new-to-me python data caching technique that I will be using a lot!

Apologies to the folks who have been enjoying my Roleplaying and Tabletop topics, I will return to those soon I promise.

Why Have Static JSON?

My use case was to be a good internet citizen.

While I have been working on some simple tools to automate repetitive tasks, I have been needing to repeatedly hit an API.

Even though I did insert delays so probably would not get rate limited or incur costs, it is still wasteful and not good practice to hammer a server over and over needlessly.

Turns out there is a really simple way to dump your dictionary as JSON and an as easy method to read that JSON back in.

Previously I had used Pickle for this, but I enjoy the elegance of this approach so I thought I would share.

Headless Web

Another good use of static JSON files is for any time you want to have a statically generated but dynamic website.

There is a growing trend in going back to decoupling the content management system from your web front end, due to the need for speed.

Consider our blogs here on the Hive blockchain. The only time the article content data needs to change is when we intentionally edit our articles. For me, that is once per day unless I have a typo.

If the server has to process code to pull the content from the blockchain or a database on every view, that is a waste.

Now consider offline use, for example on a tablet that is not connected to the internet. Or perhaps a game that has no need to be using mobile data.

Dump Your Dictionary

First, you need to extract the JSON from your dictionary and pass it to a file.

Import the JSON library and call the json.dump function. Your first parameter needs to be your dictionary object and the next is a reference to a file, in this case I open the file for writing right in the statement:

json.dump(dbstore,open("dump.json", "w"))

Reading the JSON Back

All being well, your file should now be happily sitting in the local directory, so we should be able to read it right back in.

For this we use the .load() method, passing in a file reference again.

Python then does the arranging and populating of your data to match the structure of the JSON we are passing in, making it essentially a replica of the original.

import json
 
# Opening JSON file
f = open('dump.json')
 
# returns JSON object as
# a dictionary
data = json.load(f)
 
# Iterating through the json
# list
for i in data['world_name']:
    print(i)
 
# Closing file
f.close()


0
0
0.000
2 comments
avatar

I recommend using context manager “with”. Helps ensure you close resources but it is also cleaner.

with open("readme.txt") as file:
  data = file.read()

0
0
0.000
avatar

Oh, nice tip - thanks!

This kind of thing will get super important when I put my code into production

0
0
0.000