Member-only story
How to Work With JSON Files in Python
Read from and write to JSON files using Python
Most of the time, we find JSON objects in a file, which is why today, I will tell you about how to read and write JSON files using only Python.
Article Map
In order for you to have an overview of this article, I wrote this little map that will show you what we will do in this tutorial.
- Overview of the JSON module.
- Example of a JSON file.
- JSON file structure.
- Read JSON using the
json
module. - Write JSON objects in JSON files.
- The main usage of JSON files and objects.
- Alternative usage of JSON files.
Now that you have seen more specifically what we will do in the tutorial, you are ready to start working with JSON using Python.
Python’s JSON Module
To work with JSON (string or file containing JSON object), you can use Python’s json
module. You need to import the module before you can use it.
Here there is the official JSON documentation, but before going to the next step, I would like to show you the two functions of the json
module that we will use most:
json.load()
json.dump()
As you may have guessed, we will use the load()
function to read JSON files, and the dump()
one to write JSON files.
Example of a JSON File
In order for you to understand how JSON works, here is an example of a simple JSON file: