0Pricing
Python Academy · Lesson

JSON Encoding and Decoding

Use json.loads, json.dumps, and json.load/dump for JSON I/O.

JSON Encoding and Decoding is a free Python Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

Python's json module converts between Python objects and JSON strings or files with simple, consistent functions.

json.dumps()

json.dumps(obj) serializes a Python object to a JSON string. indent=2 pretty-prints it.
import json
d = {'name': 'Alice', 'age': 30, 'active': True}
print(json.dumps(d, indent=2))

json.loads()

json.loads(s) parses a JSON string into a Python object. JSON objects become dicts, arrays become lists.
import json
s = '{"name": "Alice", "scores": [90, 85]}'
data = json.loads(s)
print(type(data), data['name'])

json.dump() to File

json.dump(obj, file_object) serializes directly to a file. No need to capture a string first.
import json, tempfile, os
tmp = tempfile.mktemp(suffix='.json')
with open(tmp, 'w') as f:
    json.dump({'x': 1}, f, indent=2)
print(open(tmp).read())
os.unlink(tmp)

json.load() from File

json.load(file_object) parses JSON directly from an open file object.
import json, io
buf = io.StringIO('{"key": "value"}')
data = json.load(buf)
print(data)

JSON Type Mapping

JSON object→dict. array→list. string→str. number→int/float. true/false→True/False. null→None.
import json
s = '[1, "two", true, null, {"a": 3.14}]'
print(json.loads(s))

Non-Serializable Types

datetime, set, bytes are not JSON-serializable. Provide a default= function or subclass JSONEncoder.
import json
from datetime import datetime
def default(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f'{type(obj)} not serializable')
print(json.dumps({'ts': datetime.now()}, default=default))

sort_keys and separators

sort_keys=True sorts dict keys. separators=(',', ':') removes whitespace for compact output.
import json
d = {'z': 3, 'a': 1, 'm': 2}
print(json.dumps(d, sort_keys=True, separators=(',', ':')))

Pretty Printing

json.dumps(obj, indent=4, ensure_ascii=False) produces human-readable JSON with Unicode preserved.
import json
d = {'name': 'Mehmet', 'city': 'Istanbul'}
print(json.dumps(d, indent=4, ensure_ascii=False))

JSONDecodeError

json.loads(invalid) raises json.JSONDecodeError. Always wrap in try/except when parsing user input.
import json
try:
    json.loads('{bad json}')
except json.JSONDecodeError as e:
    print(f'Parse error: {e}')

Updating JSON Files

Read → modify → write back: the standard pattern for updating a JSON config file.
import json, io
buf = io.StringIO('{"count": 5}')
data = json.load(buf)
data['count'] += 1
print(json.dumps(data))

Quick Check

Which function parses a JSON string into a Python object?

Recap

json.dumps/loads for strings, json.dump/load for files. Types: object→dict, array→list, null→None. Custom serialization via default= function.

Keep Going

Keep it up! Move on to the next lesson.

Frequently asked questions

Is the “JSON Encoding and Decoding” lesson free?

Yes — the full text of “JSON Encoding and Decoding” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “JSON Encoding and Decoding”?

Use json.loads, json.dumps, and json.load/dump for JSON I/O. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “JSON Encoding and Decoding” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. JSON Encoding and Decoding
  2. Handling Nested JSON Structures
  3. Reading CSV with csv.reader
  4. Writing CSV with csv.DictWriter
← Back to Python Academy