Ad – 728Γ—90
πŸ”§ Intermediate

Python JSON – Reading, Writing, and Converting JSON Data

JSON (JavaScript Object Notation) is the universal data format for APIs and configuration files. Python's built-in json module makes it trivial to parse JSON into Python dicts/lists and serialise Python objects back to JSON strings.

⏱️ 20 min read🎯 IntermediateπŸ“… Updated 2026

Parsing JSON Strings – json.loads()

json.loads() converts a JSON string into Python objects.

Python
import json

json_string = '''{
    "name": "Alice",
    "age": 30,
    "skills": ["Python", "SQL"],
    "active": true
}'''

data = json.loads(json_string)

print(data["name"])    # Alice
print(data["age"])     # 30
print(data["skills"])  # ['Python', 'SQL']
print(type(data))      # 
β–Ά Output
Alice 30 ['Python', 'SQL']

Converting to JSON String – json.dumps()

json.dumps() converts Python objects to a JSON string.

Python
import json

python_dict = {
    "name": "Bob",
    "scores": [95, 87, 92],
    "passed": True,
    "grade": None
}

# Basic conversion
json_str = json.dumps(python_dict)
print(json_str)

# Pretty-printed with indentation
pretty = json.dumps(python_dict, indent=2)
print(pretty)
β–Ά Output
{"name": "Bob", "scores": [95, 87, 92], "passed": true, "grade": null} { "name": "Bob", "scores": [95, 87, 92], "passed": true, "grade": null }

Reading and Writing JSON Files

Use json.load() and json.dump() for file operations.

Python
import json

# Write JSON to file
data = {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

# Read JSON from file
with open("data.json", "r") as f:
    loaded = json.load(f)

print(loaded["users"][0]["name"])  # Alice
Ad – 336Γ—280

Real-World: Processing API Responses

Most web APIs return JSON. Here is the standard pattern for consuming one.

Python
import json
import urllib.request

# Fetch from a public API
url = "https://api.github.com/users/python"

with urllib.request.urlopen(url) as response:
    data = json.loads(response.read())

print(data["name"])         # Python
print(data["public_repos"]) # number of repos
print(data["followers"])    # follower count

Python ↔ JSON Type Mapping

JSON has a limited set of types. Python converts automatically.

Python
# Python β†’ JSON type mapping:
# dict     β†’ object   {}
# list     β†’ array    []
# str      β†’ string   ""
# int/float→ number   42, 3.14
# True     β†’ true
# False    β†’ false
# None     β†’ null

# Verify:
print(json.dumps({"a": True, "b": None, "c": [1,2]}))
β–Ά Output
{"a": true, "b": null, "c": [1, 2]}