Academic Block

Working with JSONGet Certified

What Is JSON?

JSON (JavaScript Object Notation) is a lightweight text format for storing and exchanging data. It is easy for humans to read and write, and easy for programs to parse. Python’s built-in json module lets you convert between Python objects (dictionaries, lists, strings, numbers, booleans, and None) and JSON strings. JSON is widely used in web APIs, configuration files, and data exchange between different systems.

In Python you mainly use two functions: json.dumps() to turn a Python object into a JSON string, and json.loads() to turn a JSON string back into a Python object. Because this tutorial runs in the browser, all examples work with strings in memory rather than reading or writing real files on disk.

Converting Python to JSON with dumps

The function json.dumps() (dump string) takes a Python object and returns its JSON representation as a string. Dictionaries become JSON objects, lists become JSON arrays, and Python’s True, False, and None become true, false, and null. This is the first step whenever you need to send data to another program or store it in a text format.

Try It: Simple Dictionary to JSON

What this code does: Maya in Seattle creates a small dictionary that describes a student. She converts it to a JSON string with json.dumps and then prints both the original Python object and the resulting JSON text so you can see the difference in syntax.
import json

student = {
    "name": "Maya",
    "city": "Seattle",
    "grade": 11,
    "active": True
}

json_text = json.dumps(student)
print("Python dictionary:")
print(student)
print()
print("JSON string:")
print(json_text)

Try It: Pretty-Printing with indent

What this code does: Jordan in Austin converts the same kind of data but asks for indented output. The indent parameter makes the JSON much easier to read by adding newlines and spaces. This is the style you normally see in configuration files and API documentation.
import json

player = {
    "name": "Jordan",
    "city": "Austin",
    "points": 24,
    "starter": True
}

pretty = json.dumps(player, indent=2)
print(pretty)

Converting JSON to Python with loads

The function json.loads() (load string) takes a JSON-formatted string and returns the matching Python object. JSON objects become dictionaries, arrays become lists, and the special values true, false, and null become True, False, and None. This is how you turn data received from a web API or a configuration file back into something you can work with in Python.

Try It: JSON String to Dictionary

What this code does: Taylor in Chicago starts with a JSON string that describes a book. After calling json.loads, the data becomes a normal Python dictionary. The program then prints individual fields to show that you can access the values with ordinary dictionary syntax.
import json

json_text = '{"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "year": 1925}'

book = json.loads(json_text)
print("Title:", book["title"])
print("Author:", book["author"])
print("Year:", book["year"])
print("Type of book variable:", type(book))

Working with Lists of Objects

Real data is often a list of similar records. In JSON this appears as an array of objects. In Python it becomes a list of dictionaries. You can loop over the list just like any other Python list and read or update the fields of each dictionary.

Try It: List of Students

What this code does: Riley in Denver has a JSON array that holds three student records. After loading the data, the program loops through the list and prints each student’s name and city. This pattern is very common when you receive a collection of items from an API.
import json

json_text = '''
[
  {"name": "Riley", "city": "Denver", "grade": 10},
  {"name": "Casey", "city": "Boston", "grade": 11},
  {"name": "Avery", "city": "Portland", "grade": 12}
]
'''

students = json.loads(json_text)
for s in students:
    print(s["name"], "lives in", s["city"])

Nested Data

JSON objects can contain other objects or arrays. After loading, you navigate the structure with successive key lookups or indexes. Nested data is common in API responses that include an address inside a person, or a list of scores inside a student record.

Try It: Nested Dictionary

What this code does: Quinn in Minneapolis works with a JSON object that contains an address dictionary. After parsing, the program reaches into the nested structure to print the street and the city. This shows how to walk through multiple levels of keys.
import json

json_text = '''
{
  "name": "Quinn",
  "address": {
    "street": "14th Avenue",
    "city": "Minneapolis",
    "zip": "55404"
  }
}
'''

data = json.loads(json_text)
print("Name:", data["name"])
print("Street:", data["address"]["street"])
print("City:", data["address"]["city"])

Handling Invalid JSON

If the text you pass to json.loads is not valid JSON, Python raises a json.JSONDecodeError. Catching this exception lets your program report a clear message instead of crashing. Always validate external data before you trust it.

Try It: Catching JSONDecodeError

What this code does: Hayden in Dallas tries to parse a string that is missing a closing quote. The json.loads call raises JSONDecodeError. The except block catches it and prints a friendly message so the rest of the program can continue.
import json

bad_text = '{"name": "Hayden", "city": "Dallas"'

try:
    data = json.loads(bad_text)
    print(data)
except json.JSONDecodeError as err:
    print("Could not parse JSON.")
    print("Reason:", err)

Building JSON from Python Data

You can start with ordinary Python lists and dictionaries, modify them with normal Python code, and then turn the final structure into JSON whenever you need to save or send it. This workflow is common when you collect data step by step and only serialize it at the end.

Try It: Build and Serialize

What this code does: Cameron in Chicago starts with an empty list, appends two player dictionaries, and finally converts the whole list to a pretty-printed JSON string. The example shows the complete cycle of creating data in Python and then exporting it.
import json

players = []
players.append({"name": "Cameron", "city": "Chicago", "score": 18})
players.append({"name": "Parker", "city": "Dallas", "score": 22})

json_text = json.dumps(players, indent=2)
print(json_text)
print()
print("Number of players:", len(players))

Try It: Updating Values Before Saving

What this code does: Reese in Seattle loads a small JSON record, changes one field, adds a new field, and then converts the updated dictionary back to JSON. This demonstrates the typical read-modify-write pattern used when you need to edit data.
import json

json_text = '{"name": "Reese", "city": "Seattle", "score": 15}'
data = json.loads(json_text)

data["score"] = 19
data["level"] = "varsity"

updated = json.dumps(data, indent=2)
print(updated)

Useful Tips

  • Always use double quotes for strings inside JSON; single quotes are not valid.
  • True, False, and None in Python become true, false, and null in JSON.
  • Use indent=2 (or 4) with dumps when you want readable output.
  • Catch json.JSONDecodeError when the source of the text might be invalid.
  • After loading, treat the result as ordinary Python lists and dictionaries.

Key Takeaways

  • JSON is a text format for exchanging structured data.
  • json.dumps converts a Python object into a JSON string.
  • json.loads converts a JSON string back into a Python object.
  • Dictionaries become JSON objects; lists become JSON arrays.
  • Use indent for pretty-printed, human-readable JSON.
  • Always handle JSONDecodeError when parsing data from outside your program.

Frequently Asked Questions

What is the difference between dumps and loads?

dumps (dump string) takes a Python object and returns a JSON-formatted string. loads (load string) takes a JSON-formatted string and returns a Python object. They are opposite operations.

Why do I see true/false/null instead of True/False/None?

JSON has its own keywords. When you use dumps, Python’s True, False, and None are automatically translated to the JSON values true, false, and null. loads performs the reverse translation.

Can I use single quotes in JSON?

No. The JSON standard requires double quotes around strings and keys. Single quotes will cause json.loads to raise JSONDecodeError.

What does the indent parameter do?

When you pass indent=2 (or another positive integer) to json.dumps, the resulting string is formatted with newlines and indentation. This makes the JSON much easier for humans to read.

How do I handle nested JSON?

After loading, nested objects become nested dictionaries. Access them with successive keys, for example data[“address”][“city”]. Nested arrays become lists that you can index or loop over.

What exception should I catch for bad JSON?

Catch json.JSONDecodeError. It is raised when the text passed to loads is not valid JSON. The exception object contains details about where the problem was detected.

Can JSON store Python sets or tuples?

JSON only supports objects, arrays, strings, numbers, booleans, and null. If you pass a set or tuple to dumps you will get a TypeError. Convert them to lists first if you need to serialize them.

Is the order of keys preserved?

In modern Python (3.7+) dictionaries keep insertion order, and json.dumps respects that order. Older versions of Python did not guarantee order, but current versions do.

Ready for the next step?Learn how to search and match text patterns.
Next: Regular Expressions →