Hackforge Academy

Category: python

Python to JSON

Published on 24 Jul 2026

Explanation

JSON (JavaScript Object Notation) is a lightweight data-interchange format used to exchange data between applications. It is easy for humans

Code:

import json

student = {
    'id': 101,
    'name': 'John',
    'course': 'Python'
}

print(student)
print(type(student))

Explanation

The json.dumps() method converts a Python object into a JSON-formatted string. This is useful when sending data to APIs, storing

Code:

import json

student = {
    'id': 101,
    'name': 'Alice',
    'marks': 92
}

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

print(json_data)
print(type(json_data))

Explanation

The json.loads() method converts a JSON string into a Python object such as a dictionary or list. This is commonly

Code:

import json

json_string = '{"id":101,"name":"David","city":"Chennai"}'

student = json.loads(json_string)

print(student)
print(type(student))

print(student['name'])

Explanation

Python provides json.dump() to write Python objects directly to a JSON file and json.load() to read JSON data from a

Code:

import json

student = {
    'id': 201,
    'name': 'Praveen',
    'course': 'Full Stack Python'
}

# Write JSON to file
with open('student.json', 'w') as file:
    json.dump(student, file, indent=4)

# Read JSON from file
with open('student.json', 'r') as file:
    data = json.load(file)

print(data)
print(data['course'])

Explanation

JSON is widely used to store structured data such as employee records, product catalogs, customer information, and student details. In

Code:

import json

students = [
    {
        'id': 101,
        'name': 'John',
        'marks': 85
    },
    {
        'id': 102,
        'name': 'Alice',
        'marks': 90
    },
    {
        'id': 103,
        'name': 'David',
        'marks': 78
    }
]

with open('students.json', 'w') as file:
    json.dump(students, file, indent=4)

with open('students.json', 'r') as file:
    records = json.load(file)

for student in records:
    print(student['id'], student['name'], student['marks'])

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community