Course Progress49%
🍎 Python Basics Topic 49 / 100
⏳ 7 min read

Working with JSON

Parse and create JSON — the universal data format used by every API, config file, and web service on the planet.

"JSON is the language that APIs speak. Learn to read and write it in Python and you can work with almost any data source on the internet."

— ShurAI

What is JSON?

JSON (JavaScript Object Notation) is a text format for storing and sending data. It looks almost identical to Python dictionaries and lists, which makes it very easy to work with:

JSON (text format)
{
  "name": "Riya",
  "score": 92,
  "passed": true,
  "subjects": ["Math","CS"]
}
Python equivalent
{
  "name": "Riya",
  "score": 92,
  "passed": True,
  "subjects": ["Math","CS"]
}
Two tiny differences: JSON vs Python

true / false / null in JSON become True / False / None in Python. Python’s json module handles this conversion automatically.

json.dumps() — Python → JSON String

dumps = “dump to string”. Converts a Python dict or list to a JSON-formatted string:

python
import json

student = {
    "name"   : "Riya",
    "score"  : 92,
    "passed" : True,
    "subjects": ["Math", "CS"]
}

# Convert to JSON string
json_str = json.dumps(student)
print(json_str)
# {"name": "Riya", "score": 92, "passed": true, "subjects": ["Math", "CS"]}

# Pretty-print with indentation
print(json.dumps(student, indent=2))
output of indent=2
{
  "name": "Riya",
  "score": 92,
  "passed": true,
  "subjects": [
    "Math",
    "CS"
  ]
}

json.loads() — JSON String → Python

loads = “load from string”. Parses a JSON string and gives you a Python dict:

python
json_text = '{"name": "Arjun", "score": 75, "passed": true}'

# Parse the string into a Python dict
data = json.loads(json_text)

print(data["name"])    # Arjun
print(data["score"])   # 75
print(data["passed"])  # True  — JSON true became Python True
print(type(data))       # <class 'dict'>

json.dump() / json.load() — Working with Files

Use dump() and load() (without the ’s’) to read/write directly to a file:

python
import json

config = {
    "theme"   : "dark",
    "language": "en",
    "version" : 2,
    "features": ["bookmarks", "streaks"]
}

# WRITE to a file
with open("config.json", "w") as f:
    json.dump(config, f, indent=2)

# READ from a file
with open("config.json", "r") as f:
    loaded = json.load(f)

print(loaded["theme"])     # dark
print(loaded["features"])  # [’bookmarks’, ’streaks’]

Four Functions — Quick Reference

Function Direction Works with
json.dumps(obj)Python → JSON stringIn-memory strings
json.loads(str)JSON string → PythonIn-memory strings
json.dump(obj, f)Python → JSON fileFile objects
json.load(f)JSON file → PythonFile objects

Real Example — Save and Load a High Score

python
import json, os

def load_scores():
    if os.path.exists("scores.json"):
        with open("scores.json") as f:
            return json.load(f)
    return {}   # no file yet

def save_score(name, score):
    scores = load_scores()
    if score > scores.get(name, 0):
        scores[name] = score
        with open("scores.json", "w") as f:
            json.dump(scores, f, indent=2)
        print(f"New high score for {name}: {score}!")
    else:
        print(f"{name}’s best is still {scores[name]}")

save_score("Riya",  450)
save_score("Arjun", 380)
save_score("Riya",  520)   # beats previous 450
save_score("Riya",  490)   # doesn’t beat 520
output
New high score for Riya: 450!
New high score for Arjun: 380!
New high score for Riya: 520!
Riya’s best is still 520

"Remember: ‘s’ means string. dumps and loads work with strings in memory. Without the ‘s’, dump and load work with files."

— ShurAI

🧠 Quiz — Q1

What does json.dumps(data) do?

🧠 Quiz — Q2

What is the difference between json.dump() and json.dumps()?

🧠 Quiz — Q3

How does JSON true appear in Python after parsing?

🧠 Quiz — Q4

You receive JSON data from an API as a string. Which function converts it to a Python dict?