Python Basics — Day 13 JSON (JavaScript Object Notation)
Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey
Building skills in Python and full-stack development, with a focus on web apps and system design
Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering
From Python basics to full-stack projects, sharing my progress as I grow into a developer
Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development
01. What is JSON?
A lightweight data format that is easy to read and write
Very similar to Python dictionaries
Widely used for APIs, data storage, and configuration files
{
"name": "Sabin",
"age": 30,
"skills": ["Python", "Flask", "React"]
}
02. Working with JSON in Python
Python provides the built-in json module for handling JSON.
import json
03. Converting Between JSON and Python Objects
JSON → Python
import json
data = '{"name": "Sabin", "age": 30}' # JSON string
py_obj = json.loads(data) # JSON string → dict
print(py_obj) # {'name': 'Sabin', 'age': 30}
print(py_obj["name"]) # Sabin
Python → JSON
person = {"name": "Sabin", "age": 30}
json_str = json.dumps(person, ensure_ascii=False)
print(json_str) # {"name": "Sabin", "age": 30}
04. Reading & Writing JSON Files
Save to File
person = {"name": "Sabin", "age": 30, "skills": ["Python", "Flask"]}
with open("person.json", "w", encoding="utf-8") as f:
json.dump(person, f, ensure_ascii=False, indent=2)
👉 indent=2 : pretty formatting with indentation
👉 ensure_ascii=False : prevents non-ASCII characters (e.g., Korean) from breaking
Load from File
with open("person.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data) # {'name': 'Sabin', 'age': 30, 'skills': ['Python', 'Flask']}
print(data["skills"]) # ['Python', 'Flask']
05. JSON with Lists
people = [
{"name": "Tom", "age": 20},
{"name": "Anna", "age": 22}
]
with open("people.json", "w", encoding="utf-8") as f:
json.dump(people, f, ensure_ascii=False, indent=2)
with open("people.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded[0]["name"]) # Tom
06. Practice Examples
Example 1: Convert Dictionary to JSON String
book = {"title": "Python Basics", "price": 25000}
json_str = json.dumps(book, ensure_ascii=False)
print(json_str)
Example 2: Convert JSON String to Dictionary
json_data = '{"title": "AI Guide", "author": "Sabin"}'
book = json.loads(json_data)
print(book["author"])