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
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
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
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
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
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
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
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
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.JSONDecodeErrorwhen 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.dumpsconverts a Python object into a JSON string.json.loadsconverts 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.