Learn Python in 30 Days — Day 23 – Working with JSON

Day 23: Working with JSON

Welcome to Day 23 of the Learn Python in 30 Days series!

Welcome back! Today we move beyond plain text files and learn how to work with JSON, one of the most important data formats in modern programming.

JSON is everywhere in APIs, configuration files, save files, websites, apps, IoT devices, games and many more.
Understanding it now sets you up for real-world coding later.

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

What is JSON?

JSON stands for JavaScript Object Notation
Think of JSON as:

  • Cleaner than plain text

  • More organised than CSV

  • Easier to read/write than XML

JSON stores structured data using the same shapes you already know:

JSON

Python

Object

Dictionary

Array

List

String

String

Number

int/float

true/false

True/False

null

None

This makes JSON ideal for saving data such as settings and preferences, user profiles, high-score tables, inventory lists, anything needing structure and nested data

The Python json Module

You don’t need to install any modules, Python already includes the json module.

Import it as per Day 19: -

import json

It gives you four core functions:

Function

Purpose

json.load(file)

Read JSON from a file into Python

json.dump(data, file)

Write JSON to a file from Python

json.loads(string)

Convert a JSON string → Python

json.dumps(data)

Convert Python → JSON string

For this post, we focus on reading and writing real files.

Reading JSON Files

Let’s say you have a file called settings.json and it contains the following:

{ "volume": 70, "fullscreen": true, "player_name": "Matty" }

To load it in Python we do the following:

import json with open("rsettings.json", "r") as file: data = json.load(file) print(data)

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub readjson.py and rsettings.json and run it yourself.

What happens here?

  • open("rsettings.json", "r") opens the file in read mode

  • json.load(file) takes the JSON and turns it into a Python dictionary

  • data now behaves like any normal Python dict

Accessing values singular values of the data can be done by: -

print(data["volume"]) print(data["player_name"])

Writing JSON Files

Start with a normal Python dictionary:

settings = { "volume": 100, "fullscreen": False, "player_name": "Nova" }

To save it as JSON:

with open("wsettings.json", "w") as file: json.dump(settings, file, indent=4)

Why indent=4?

It formats the file neatly:

{ "volume": 100, "fullscreen": false, "player_name": "Nova" }

If you skip the indent, you get one long unreadable line, though machines don’t care, but humans do.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub writejson.py and run it yourself.

Updating JSON file

Working with JSON usually follows this pattern:

  1. Load the file

  2. Modify the dictionary

  3. Write it back

This is fairly simple and can be seen in the following example:

with open("rsettings.json", "r") as file: data = json.load(file) data["volume"] = 50 data["fullscreen"] = True with open("rsettings.json", "w") as file: json.dump(data, file, indent=4)

This is the everyday workflow in apps, games, and scripts.

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub updatejson.py and rsettings.json and run it yourself.

Handling Missing Files

If the JSON file doesn’t exist yet, Python would normally crash.

You can prevent that using error handling:

import json try: with open("settings.json", "r") as file: data = json.load(file) except FileNotFoundError: data = { "volume": 70, "fullscreen": False, "player_name": "New Player" }

This is essential for:

  • first-run app startup

  • games with no save file yet

  • programs that generate their own settings

Try it yourself, hopefully you'll see something like that shown below: -

You can also download this example from my GitHub
missingfile.py and run it yourself.

Converting Between JSON Strings and Python Data

Sometimes JSON comes from APIs, not files.

You can convert a JSON string into Python:

json_text = '{"score": 1200, "active": true}' data = json.loads(json_text)

And convert Python data back into JSON text:

json_string = json.dumps(data) print(json_string)

This is useful for:

  • sending data over a network

  • embedding JSON inside files

  • debugging or logging

A runnable example is given below: -

import json

# --- JSON string coming from somewhere (API, network, embedded text) ---
json_text = '{"score": 1200, "active": true, "items": ["sword", "shield"]}'

# Convert JSON string → Python dictionary
data = json.loads(json_text)

print("Python data:")
print(data)
print(type(data))   # Should be <class 'dict'>

# Modify the data (just to show it's normal Python)
data["score"] += 300
data["active"] = False
data["items"].append("health potion")

# Convert Python dictionary → JSON string
json_string = json.dumps(data)

print("\nBack to JSON string:")
print(json_string)
print(type(json_string))   # Should be <class 'str'>

Try it yourself, hopefully you'll see something like that shown below: -
You can also download this example from my GitHub convert.py and run it yourself.

Why JSON Matters Going Forward

From here on, JSON becomes part of your toolbox for:

  • saving progress

  • storing inventory or player stats

  • keeping configuration files

  • working with APIs in future Python projects

  • passing data between Python and JavaScript

  • storing structured data without a database

Next Up — Day 24 – Intro to Classes & Objects

Tomorrow, you’ll look into making simple class with __init__() and methods.

All example files for this series are available on my GitHub: Learn-Python-in-30-Days

You can see the full series here Learn Python in 30 Days series!

Hope you have enjoyed this post, thanks Matty

Comments

Popular posts from this blog

6502 - Part 2 Reset and Clock Circuit

Math Behind Logic Gates

Building a 6502 NOP Test