Course topics

By WebNest Studio Engineering Team

Python Tutorial

Working with JSON in Python

JSON (JavaScript Object Notation) is a lightweight, text-based data format widely used for storing configuration data and exchanging information between programs — especially over the web via APIs. Python's built-in json module provides a direct, well-defined mapping between JSON text and native Python data structures.

Because JSON's structure (objects, arrays, strings, numbers, booleans, and null) maps almost one-to-one onto Python's own dictionaries, lists, strings, numbers, booleans, and None, converting between the two formats is usually simple and predictable.

Why it matters

JSON is the format in which web APIs send and receive data, and it is also widely used for configuration files. Every time a Python program talks to a web service, it converts dictionaries to JSON text and back. The mapping between the two is close, but the few differences are worth knowing before they cause a bug.

Converting Python to JSON: json.dumps()

json.dumps(obj) serializes a Python object into a JSON-formatted string. It accepts useful keyword arguments such as indent=4 for pretty-printed, human-readable output, and sort_keys=True to order dictionary keys alphabetically. To write JSON directly to a file instead of returning a string, use json.dump(obj, file).

Converting JSON to Python: json.loads()

json.loads(text) parses a JSON-formatted string and returns the equivalent Python object. To read JSON directly from an already-open file object instead of a string, use json.load(file). If the text is not valid JSON, both functions raise a json.JSONDecodeError.

The Type Mapping Between JSON and Python

Understanding exactly how types translate in each direction avoids confusion when working with parsed data.

  • JSON object {} ↔ Python dict
  • JSON array [] ↔ Python list
  • JSON string "..." ↔ Python str
  • JSON number (integer or decimal) ↔ Python int or float
  • JSON true / false ↔ Python True / False
  • JSON null ↔ Python None

Examples

Serializing a Python dictionary to a JSON string

Python
import json

person = {
    "name": "Elena",
    "age": 31,
    "is_member": True,
    "languages": ["Python", "SQL"],
    "manager": None,
}

json_text = json.dumps(person, indent=2)
print(json_text)
Output
{
  "name": "Elena",
  "age": 31,
  "is_member": true,
  "languages": [
    "Python",
    "SQL"
  ],
  "manager": null
}

Parsing a JSON string back into Python objects

Python
import json

data = '{"name": "Elena", "age": 31, "languages": ["Python", "SQL"]}'
parsed = json.loads(data)

print(type(parsed))
print(parsed["name"])
print(parsed["languages"][0])
print(parsed["age"] + 1)
Output
<class 'dict'>
Elena
Python
32

Common Mistakes

  • Confusing JSON's true/false/null with Python's True/False/None when hand-writing JSON text — JSON requires the lowercase forms.
  • Trying to serialize a Python object that json.dumps() does not know how to handle (like a custom class instance or a set), which raises a TypeError unless a custom encoder is supplied.
  • Assuming json.loads() returns the exact same object identities or key order guarantees across all Python/JSON tooling, rather than just an equivalent structure.
  • Forgetting that JSON keys are always strings — a Python dict with integer keys will have those keys converted to strings when serialized.

Exercise

Convert the dictionary to a JSON string and print it. Then parse the JSON text given below and print the Python type of its price and the value of its tags.

Expected output: {"name": "Asha", "skills": ["python", "sql"], "active": true} then float None

Python · starter code
import json

user = {"name": "Asha", "skills": ["python", "sql"], "active": True}
# TODO: print the dictionary as a JSON string

text = '{"price": 12.5, "tags": null}'
# TODO: parse the text, then print the type name of price and the value of tags
Show hints
  • json.dumps(obj) returns a string and json.loads(text) returns Python objects.
  • JSON true and null correspond to Python True and None.
Show solution
Python · solution
import json

user = {"name": "Asha", "skills": ["python", "sql"], "active": True}
print(json.dumps(user))

text = '{"price": 12.5, "tags": null}'
data = json.loads(text)
print(type(data["price"]).__name__, data["tags"])

Quick quiz

1. What is the difference between json.dump and json.dumps?

  • A. There is none
  • B. dump writes to a file object; dumps returns a string
  • C. dumps writes to a file; dump returns a string
  • D. dump is for lists only
Show answer

B. The "s" stands for string. load and loads differ in the same way.

2. What does the JSON value null become in Python?

  • A. "null"
  • B. None
  • C. 0
  • D. False
Show answer

B. Likewise true and false become True and False.

3. A Python tuple is converted to JSON and back. What type is it afterwards?

  • A. tuple
  • B. list
  • C. dict
  • D. str
Show answer

B. JSON has only arrays, which are read back as lists.

Interview questions

How do Python types map to JSON?

Show answer

A dict becomes an object, a list or tuple an array, a str a string, int and float a number, True and False become true and false, and None becomes null. Dictionary keys must be strings in JSON, so other keys are converted to strings. Sets, dates and custom objects have no JSON form and raise TypeError.

How do you serialise a datetime or a custom object to JSON?

Show answer

Pass a function as the default argument of json.dumps. It is called for any object the encoder does not know and must return something serialisable, for example obj.isoformat() for a date or a dictionary of the object's fields. When reading the JSON back, the reverse conversion has to be done explicitly.

Key Points to Remember

  • json.dumps() converts a Python object to a JSON string; json.loads() parses a JSON string back into Python objects.
  • json.dump()/json.load() do the same conversions directly with an open file, instead of an in-memory string.
  • JSON objects map to dicts, arrays map to lists, and true/false/null map to True/False/None.
  • Invalid JSON text raises a json.JSONDecodeError when parsed with loads() or load().

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering