Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

JSON Files in Python

Learn how to read, write, create and work with JSON data using Python.

What is JSON?

JSON stands for JavaScript Object Notation.

JSON is a text-based format commonly used for storing and exchanging structured data.

JSON data is especially common when working with APIs, web applications and configuration files.

Simple Definition: JSON is a simple text format used to store and exchange structured data.

Simple JSON Example

{
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

Here:

  • name is a key.
  • Rahul is its value.
  • age is another key.
  • JSON stores data in key-value form.

JSON File Diagram

Python can convert data between Python objects and JSON format.

Python Object

Dictionary, List and other Python data

↓
json.dumps()

Python Object → JSON String

json.loads()

JSON String → Python Object

↓
json.dump()

Python Object → JSON File

json.load()

JSON File → Python Object

The json Module

Python provides the built-in json module for working with JSON data.

import json

The module provides functions to convert data between Python objects and JSON format.

Python Dictionary to JSON String

The json.dumps() function converts a Python object into a JSON string.

import json

student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

json_data = json.dumps(student)

print(json_data)

Output:

{"name": "Rahul", "age": 22, "course": "Python"}

JSON String to Python Dictionary

The json.loads() function converts a JSON string into a Python object.

import json

json_data = '{"name": "Rahul", "age": 22}'

student = json.loads(json_data)

print(student)
print(student["name"])

Output:

{'name': 'Rahul', 'age': 22}
Rahul

Writing JSON Data to a File

The json.dump() function writes a Python object directly into a JSON file.

import json

student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

with open(
    "student.json",
    "w",
    encoding="utf-8"
) as file:

    json.dump(
        student,
        file
    )

A file named student.json is created.

Writing Pretty JSON

We can use indent to make JSON data easier to read.

import json

student = {
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

with open(
    "student.json",
    "w",
    encoding="utf-8"
) as file:

    json.dump(
        student,
        file,
        indent=4
    )

The JSON file will look similar to:

{
    "name": "Rahul",
    "age": 22,
    "course": "Python"
}

Reading a JSON File

The json.load() function reads JSON data from a file and converts it into a Python object.

import json

with open(
    "student.json",
    "r",
    encoding="utf-8"
) as file:

    student = json.load(file)

print(student)

Output:

{'name': 'Rahul', 'age': 22, 'course': 'Python'}

Accessing JSON Data

import json

with open(
    "student.json",
    "r",
    encoding="utf-8"
) as file:

    student = json.load(file)

print("Name:", student["name"])
print("Age:", student["age"])
print("Course:", student["course"])

Output:

Name: Rahul
Age: 22
Course: Python

Working with JSON Lists

JSON can also store arrays, which are represented by Python lists after loading.

import json

students = [
    {
        "name": "Rahul",
        "course": "Python"
    },
    {
        "name": "Priya",
        "course": "Java"
    },
    {
        "name": "Amit",
        "course": ".NET"
    }
]

with open(
    "students.json",
    "w",
    encoding="utf-8"
) as file:

    json.dump(
        students,
        file,
        indent=4
    )

Reading a JSON List

import json

with open(
    "students.json",
    "r",
    encoding="utf-8"
) as file:

    students = json.load(file)

for student in students:

    print(
        student["name"],
        student["course"]
    )

Output:

Rahul Python
Priya Java
Amit .NET

Python and JSON Data Types

Python JSON
dict object
list array
str string
int / float number
True true
False false
None null

Formatting JSON Data

The indent parameter makes JSON output easier to read.

import json

data = {
    "name": "Rahul",
    "age": 22,
    "skills": [
        "Python",
        "SQL"
    ]
}

print(
    json.dumps(
        data,
        indent=4
    )
)

Sorting JSON Keys

The sort_keys=True option sorts dictionary keys when producing JSON output.

import json

data = {
    "course": "Python",
    "age": 22,
    "name": "Rahul"
}

print(
    json.dumps(
        data,
        indent=4,
        sort_keys=True
    )
)
Output
{
    "age": 22,
    "course": "Python",
    "name": "Rahul"
}

Updating JSON Data

We can read a JSON file, modify the Python object and write the updated object back to the file.

import json

with open(
    "student.json",
    "r",
    encoding="utf-8"
) as file:

    student = json.load(file)


student["course"] = "Python Full Stack"


with open(
    "student.json",
    "w",
    encoding="utf-8"
) as file:

    json.dump(
        student,
        file,
        indent=4
    )

The course value is updated and the new data is saved.

Searching JSON Data

We can read a list of objects and search for a specific value.

import json

with open(
    "students.json",
    "r",
    encoding="utf-8"
) as file:

    students = json.load(file)


for student in students:

    if student["name"] == "Rahul":

        print("Student found")
        print(student)
Output
Student found
{'name': 'Rahul', 'course': 'Python', 'fees': 35000}

Handling JSON Errors

Invalid JSON text can cause a JSONDecodeError.

import json

try:

    data = json.loads(
        '{"name": "Rahul"}'
    )

    print(data)

except json.JSONDecodeError:

    print("Invalid JSON data")

Exception handling helps prevent the program from stopping unexpectedly when JSON data is invalid.

Output
{'name': 'Rahul'}

JSON and APIs

JSON is commonly used to exchange structured data between applications and APIs.

{
    "id": 101,
    "name": "Rahul",
    "course": "Python",
    "status": "active"
}

Python applications can load this JSON data, process it and use the values in the application.

CSV vs JSON

CSV JSON
Good for tabular data. Good for structured and nested data.
Uses rows and columns. Uses objects and arrays.
Simple text format. Supports nested structures.
Common in spreadsheets and data exports. Common in APIs and web applications.

Common JSON Functions

Function Purpose
json.dumps() Convert Python object to JSON string.
json.loads() Convert JSON string to Python object.
json.dump() Write Python object to JSON file.
json.load() Read JSON file into a Python object.

Example: Student JSON 📩🌍

import json

students = [
    {
        "name": "Rahul",
        "course": "Python",
        "fees": 45000
    },
    {
        "name": "Priya",
        "course": "Java",
        "fees": 40000
    },
    {
        "name": "Amit",
        "course": ".NET",
        "fees": 50000
    }
]


with open(
    "students.json",
    "w",
    encoding="utf-8"
) as file:

    json.dump(
        students,
        file,
        indent=4
    )


with open(
    "students.json",
    "r",
    encoding="utf-8"
) as file:

    data = json.load(file)


for student in data:

    print(
        student["name"],
        student["course"],
        student["fees"]
    )

Output:

Rahul Python 45000
Priya Java 40000
Amit .NET 50000

Best Practices

  • Use valid JSON syntax.
  • Use indent when human-readable JSON is required.
  • Use UTF-8 encoding for JSON text files when appropriate.
  • Handle invalid JSON data using exception handling.
  • Validate important input data before processing it.

Common Mistakes

  • Using invalid JSON syntax.
  • Forgetting that JSON uses double quotes for strings in standard JSON syntax.
  • Confusing loads() with load().
  • Confusing dumps() with dump().
  • Forgetting to open the file with the correct mode.

Practice Programs

  1. Create a Python dictionary and convert it to JSON.
  2. Convert a JSON string back to a Python dictionary.
  3. Create a students.json file.
  4. Store multiple student objects in the JSON file.
  5. Read the JSON file and print each student.
  6. Search for a student by name.
  7. Update a student's course and save the JSON file again.

Summary

JSON is a text-based format used to store and exchange structured data. Python provides the built-in json module for working with JSON. The dumps() and loads() functions work with JSON strings, while dump() and load() work with JSON files. JSON is commonly used with APIs, web applications and configuration data.