Last modified: Feb 11, 2026 By Alexander Williams
Create JSON Object in Python: A Beginner's Guide
JSON is a key data format. Python makes working with it simple. This guide shows you how.
You will learn to create, read, and write JSON objects. We use Python's built-in tools.
What is a JSON Object?
JSON stands for JavaScript Object Notation. It is a lightweight data format.
It is easy for humans to read and write. It is easy for machines to parse and generate.
JSON objects are collections of key-value pairs. They are very similar to Python dictionaries.
Understanding Python objects helps grasp these concepts.
Python's JSON Module
Python includes a module for JSON. You do not need to install anything extra.
Import it at the start of your script. Use the import json statement.
This module has two main functions. The json.dumps() function converts Python to JSON.
The json.loads() function converts JSON to Python. We will use both.
Creating a JSON Object from a Dictionary
The most common way is from a Python dictionary. A dict maps directly to a JSON object.
Let's create a simple dictionary first. Then we will convert it to a JSON string.
# Create a Python dictionary
user_data = {
"name": "Alice",
"age": 30,
"city": "New York",
"is_subscribed": True
}
print("Python Dictionary:", user_data)
print("Type:", type(user_data))
Python Dictionary: {'name': 'Alice', 'age': 30, 'city': 'New York', 'is_subscribed': True}
Type: <class 'dict'>
Now, convert this dictionary to a JSON string. Use the json.dumps() function.
import json
# Convert dictionary to a JSON string
json_string = json.dumps(user_data)
print("JSON String:", json_string)
print("Type:", type(json_string))
JSON String: {"name": "Alice", "age": 30, "city": "New York", "is_subscribed": true}
Type: <class 'str'>
Notice the changes. Python's True became JSON's true. The type is now a string.
Formatting JSON Output
The default JSON string is compact. You can format it for better readability.
Use the indent parameter in json.dumps(). It adds spaces for structure.
# Create formatted JSON with indentation
pretty_json = json.dumps(user_data, indent=4)
print("Formatted JSON:")
print(pretty_json)
Formatted JSON:
{
"name": "Alice",
"age": 30,
"city": "New York",
"is_subscribed": true
}
You can also sort the keys alphabetically. Use the sort_keys=True parameter.
Reading JSON Back into Python
Often, you receive JSON data. You need to convert it back to a Python object.
Use the json.loads() function. It parses a JSON string.
For a deeper dive, see our guide on converting JSON to Python objects.
# A sample JSON string received from an API or file
received_json = '{"product": "Laptop", "price": 999.99, "in_stock": false}'
# Convert JSON string to a Python dictionary
python_dict = json.loads(received_json)
print("Python Dictionary:", python_dict)
print("Price:", python_dict["price"])
print("Type of 'in_stock':", type(python_dict["in_stock"]))
Python Dictionary: {'product': 'Laptop', 'price': 999.99, 'in_stock': False}
Price: 999.99
Type of 'in_stock': <class 'bool'>
JSON false becomes Python False. Numbers become integers or floats.
Working with Nested JSON Objects
Real-world JSON is often nested. Objects can contain other objects or arrays.
Creating these in Python uses nested dictionaries and lists.
Learn more about structuring such data in our nested objects guide.
# Create a nested Python dictionary
company_data = {
"company": "TechCorp",
"employees": [
{"name": "Bob", "department": "Engineering"},
{"name": "Charlie", "department": "Sales"}
],
"location": {
"city": "San Francisco",
"country": "USA"
}
}
# Convert to formatted JSON
nested_json = json.dumps(company_data, indent=2)
print(nested_json)
{
"company": "TechCorp",
"employees": [
{
"name": "Bob",
"department": "Engineering"
},
{
"name": "Charlie",
"department": "Sales"
}
],
"location": {
"city": "San Francisco",
"country": "USA"
}
}
Accessing nested data uses multiple key lookups. For example: company_data["employees"][0]["name"].
Writing and Reading JSON Files
You often save JSON to a file. Or read JSON data from a file.
Use json.dump() to write to a file. Use json.load() to read from a file.
Note the missing 's' in the function names. They work with file objects.
# Data to save
data_to_save = {"task": "Learn JSON", "priority": "high"}
# Write JSON to a file
with open("data.json", "w") as json_file:
json.dump(data_to_save, json_file, indent=4)
print("Data written to 'data.json'.")
# Read JSON from a file
with open("data.json", "r") as json_file:
loaded_data = json.load(json_file)
print("Data read from file:", loaded_data)
Data written to 'data.json'.
Data read from file: {'task': 'Learn JSON', 'priority': 'high'}
Handling Custom Python Objects
The json module cannot serialize custom class objects by default.
You need to provide a way to convert them. This is called serialization.
Our detailed JSON serialization guide covers this advanced topic.
A simple method is to convert the object to a dictionary first.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def to_dict(self):
# Convert object attributes to a dictionary
return {"name": self.name, "price": self.price}
# Create an object
my_product = Product("Mouse", 25.50)
# Convert to dict, then to JSON
product_json = json.dumps(my_product.to_dict(), indent=2)
print(product_json)
{
"name": "Mouse",
"price": 25.5
}
Common Errors and Tips
TypeError: Object is not JSON serializable: This happens when you try to dump an unsupported type. Convert it to a basic type first.
JSONDecodeError: This occurs when json.loads() receives invalid JSON. Check your string for syntax errors.
Always use the with statement for file operations. It automatically closes the file.
Use meaningful key names in your dictionaries. This makes your JSON self-documenting.
Conclusion
Creating JSON objects in Python is straightforward. The json module is powerful and built-in.
Remember the core functions: dumps() and loads() for strings, dump() and load() for files.
Start with dictionaries. Use lists for arrays. Use nesting for complex structures.
This skill is vital for web APIs, configuration files, and data storage. Practice with different data shapes.
Mastering JSON in Python opens doors to modern programming. You can now exchange data with many applications.