Lesson 47 of 70 – Python JSON
67%

Python JSON

JSON stands for JavaScript Object Notation. It is a popular format used for storing and exchanging data between applications, websites, APIs, and servers.

Note: Python provides a built-in json module for working with JSON data.

What is JSON?

JSON is a lightweight data format that represents information using objects, arrays, key-value pairs, and values.

Example:

{
    "name": "Rahul",
    "age": 20,
    "city": "Patna"
}

JSON is commonly used when applications need to exchange data.

JSON Data Types

JSON supports several common data types:

  • String
  • Number
  • Boolean
  • Object
  • Array
  • Null
{
    "name": "Rahul",
    "age": 20,
    "student": true,
    "skills": ["Python", "SQL"],
    "address": {
        "city": "Patna"
    },
    "phone": null
}

Importing the JSON Module

Python includes the json module in its standard library. We can import it using:

import json

No separate installation is required.

Python Dictionary to JSON

A Python dictionary can be converted into a JSON string using json.dumps().

import json

student = {
    "name": "Rahul",
    "age": 20,
    "city": "Patna"
}

data = json.dumps(student)

print(data)

Output:

{"name": "Rahul", "age": 20, "city": "Patna"}

json.dumps()

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

import json

data = {
    "name": "Amit",
    "age": 22
}

json_data = json.dumps(data)

print(json_data)

JSON to Python Object

A JSON string can be converted into a Python object using json.loads().

import json

data = '{"name": "Rahul", "age": 20}'

student = json.loads(data)

print(student)

Output:

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

json.loads()

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

import json

data = '{"name": "Priya", "course": "Python"}'

student = json.loads(data)

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

Output:

Priya
Python

JSON Object

A JSON object is similar to a Python dictionary. It contains key-value pairs.

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

In Python, this can be represented as:

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

JSON Array

A JSON array stores multiple values. It is similar to a Python list.

{
    "name": "Rahul",
    "skills": [
        "Python",
        "SQL",
        "HTML"
    ]
}

In Python, the JSON array becomes a list.

JSON Boolean Values

JSON uses true and false for Boolean values. When converted to Python, they become True and False.

{
    "name": "Rahul",
    "active": true
}

Python representation:

{
    "name": "Rahul",
    "active": True
}

JSON null

JSON uses null to represent the absence of a value. Python uses None.

{
    "phone": null
}

After conversion to Python:

{
    "phone": None
}

Creating a JSON File

JSON data can be stored in a file using the .json extension.

import json

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

with open("student.json", "w") as file:

    json.dump(student, file)

The json.dump() function writes Python data directly to a JSON file.

json.dump()

The json.dump() function writes a Python object to a file in JSON format.

import json

data = {
    "name": "Amit",
    "age": 22
}

with open("data.json", "w") as file:

    json.dump(data, file)

json.load()

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

import json

with open("student.json", "r") as file:

    student = json.load(file)

print(student)

dump() vs dumps()

Function Purpose
json.dump() Writes JSON data to a file
json.dumps() Converts Python data into a JSON string

load() vs loads()

Function Purpose
json.load() Reads JSON data from a file
json.loads() Reads JSON data from a string

Formatting JSON with indent

The indent parameter makes JSON output easier to read.

import json

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

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

Output:

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

Sorting JSON Keys

The sort_keys=True parameter sorts dictionary keys alphabetically in the JSON output.

import json

data = {
    "city": "Patna",
    "name": "Rahul",
    "age": 20
}

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

Nested JSON Data

JSON objects can contain other objects and arrays. This is called nested JSON data.

student = {
    "name": "Rahul",
    "address": {
        "city": "Patna",
        "state": "Bihar"
    },
    "skills": [
        "Python",
        "SQL"
    ]
}

print(student["address"]["city"])
print(student["skills"][0])

Output:

Patna
Python

Converting a Python List to JSON

import json

courses = [
    "Python",
    "Java",
    "SQL",
    "HTML"
]

data = json.dumps(courses)

print(data)

Output:

["Python", "Java", "SQL", "HTML"]

Practical Example – Student JSON File

The following program creates a JSON file containing student information and then reads it back.

import json

student = {
    "id": 101,
    "name": "Rahul",
    "age": 20,
    "course": "Python",
    "skills": [
        "Python",
        "SQL"
    ]
}

# Write JSON file

with open("student.json", "w") as file:

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


# Read JSON file

with open("student.json", "r") as file:

    data = json.load(file)

print(data["name"])
print(data["course"])

Output:

Rahul
Python

JSON and APIs

JSON is commonly used by web APIs to exchange information between a client and a server.

For example, an API might return:

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

Python can use the json module to work with JSON data received from applications and APIs.

Python and JSON Conversion

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

Key Points

  • JSON stands for JavaScript Object Notation.
  • Python provides the built-in json module.
  • json.dumps() converts Python data into a JSON string.
  • json.loads() converts a JSON string into a Python object.
  • json.dump() writes JSON data to a file.
  • json.load() reads JSON data from a file.
  • JSON objects are similar to Python dictionaries.
  • JSON arrays are similar to Python lists.
  • Use indent to make JSON output easier to read.
  • JSON is widely used in web APIs and data exchange.

🧠 Quick Quiz

Question: Which Python function converts a Python object into a JSON string?