Member-only story

How to Work With JSON Files in Python

Tommaso De Ponti
Better Programming
Published in
5 min readMar 26, 2020

Photo by Chris Ried on Unsplash

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.

  1. Overview of the JSON module.
  2. Example of a JSON file.
  3. JSON file structure.
  4. Read JSON using the json module.
  5. Write JSON objects in JSON files.
  6. The main usage of JSON files and objects.
  7. 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:

JSON’s Structure

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Tommaso De Ponti
Tommaso De Ponti

Written by Tommaso De Ponti

Building stuff, #Stellar. https://tdep.xycloo.com. Check my personal blog at https://heytdep.github.io for more specific and/or advanced articles.

Responses (2)

Write a response

Line 6: Close test.json file

You don't need to close the file explicitly. with keyword does that automatically.

--

Really enjoyed reading through the article, short and simple.

--