json.dumps() Function Explained
json.dumps() converts a Python object into a JSON-formatted string.
Use it when you want JSON as text, not as a file. This is common when sending data to an API, storing JSON in a variable, or printing JSON for debugging.
Quick example
import json
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print(json_string)
Output:
{"name": "Alice", "age": 25}
Use json.dumps() when you want a JSON string, not a file. It converts Python data like dictionaries and lists into text in JSON format.
What json.dumps() does
json.dumps() takes a Python value and returns a string in JSON format.
Key points:
- It converts a Python object into a JSON string
- It returns text, not a Python dictionary or list
- It is commonly used before sending data to an API or saving JSON text
If you are new to the json module, see the Python JSON module overview.
Basic syntax
The basic form looks like this:
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, indent=None, sort_keys=False)
What this means:
objis the Python object you want to convert- The function returns a string
- Optional arguments let you format the output
A simple example:
import json
numbers = [1, 2, 3]
result = json.dumps(numbers)
print(result)
print(type(result))
Output:
[1, 2, 3]
<class 'str'>
Even though the result looks like a Python list, it is actually a string.
Python types that work with json.dumps()
Many common Python types can be converted directly.
| Python type | JSON result |
|---|---|
dict | JSON object |
list | JSON array |
tuple | JSON array |
str | JSON string |
int and float | JSON number |
True and False | true and false |
None | null |
Example:
import json
data = {
"name": "Alice",
"scores": [95, 88, 91],
"active": True,
"nickname": None
}
print(json.dumps(data))
Output:
{"name": "Alice", "scores": [95, 88, 91], "active": true, "nickname": null}
Notice these JSON differences:
- JSON uses
trueandfalse, notTrueandFalse - JSON uses
null, notNone - JSON uses double quotes for strings
Simple example
Here is a basic dictionary converted to a JSON string:
import json
person = {"name": "Bob", "age": 30}
json_text = json.dumps(person)
print(json_text)
print(type(json_text))
Output:
{"name": "Bob", "age": 30}
<class 'str'>
Important details:
- The result uses double quotes
- The result is a string
- It is JSON-formatted text, not a Python dictionary
If your goal is specifically to convert a dictionary, see how to convert a dictionary to JSON in Python.
Pretty printing with indent
By default, json.dumps() returns compact JSON on one line.
You can make it easier to read with the indent argument:
import json
data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "SQL"]
}
json_text = json.dumps(data, indent=2)
print(json_text)
Output:
{
"name": "Alice",
"age": 25,
"skills": [
"Python",
"SQL"
]
}
This is useful for:
- Debugging
- Logging
- Reading JSON more easily
It still returns a string.
If you want more formatting examples, see how to pretty print JSON in Python.
Sorting keys
Use sort_keys=True to output dictionary keys in sorted order.
import json
data = {"b": 2, "a": 1, "c": 3}
print(json.dumps(data, sort_keys=True))
Output:
{"a": 1, "b": 2, "c": 3}
This can help when:
- Comparing JSON output
- Making output more predictable
- Keeping test results consistent
You can combine it with indent:
import json
data = {"b": 2, "a": 1, "c": 3}
print(json.dumps(data, indent=2, sort_keys=True))
json.dumps() vs json.dump()
These two functions are similar, but they do different things.
json.dumps()
- Returns a JSON string
import json
data = {"name": "Alice"}
json_text = json.dumps(data)
print(json_text)
json.dump()
- Writes JSON directly to a file object
import json
data = {"name": "Alice"}
with open("data.json", "w") as file:
json.dump(data, file)
Use:
json.dumps()when you want a stringjson.dump()when you want to write to a file
For a full explanation, see json.dump() function explained.
Common errors and limits
Not every Python object can be converted by default.
These often cause problems:
set- Custom class instances
- Functions
These usually raise a TypeError.
Example with a set:
import json
data = {"numbers": {1, 2, 3}}
print(json.dumps(data))
This raises an error like:
TypeError: Object of type set is not JSON serializable
How to fix unsupported object errors
A common fix is to convert unsupported values into supported ones before calling json.dumps().
Convert a set to a list
import json
data = {"numbers": list({1, 2, 3})}
print(json.dumps(data))
Convert a custom object to a dictionary
import json
class User:
def __init__(self, name, age):
self.name = name
self.age = age
user = User("Alice", 25)
data = {
"name": user.name,
"age": user.age
}
print(json.dumps(data))
If you are seeing this error, read TypeError: Object is not JSON serializable.
Common mistakes
Beginners often run into these problems:
- Trying to convert a
setdirectly - Passing a custom object without converting it first
- Expecting
json.dumps()to write to a file - Confusing the returned JSON string with a Python dictionary
- Forgetting to import the
jsonmodule
Useful checks while debugging:
import json
data = {"name": "Alice"}
print(type(data))
print(data)
print(type(json.dumps(data)))
print(json.dumps(data, indent=2))
These help you confirm:
- What type your original data is
- What the JSON output looks like
- That
json.dumps()returns a string
FAQ
What is the difference between json.dumps() and json.loads()?
json.dumps() converts a Python object to a JSON string. json.loads() converts a JSON string back into a Python object.
See json.loads() function explained.
Does json.dumps() return a dictionary?
No. It returns a string that contains JSON-formatted text.
Can json.dumps() write to a file?
No. Use json.dump() if you want to write JSON directly to a file.
Why does json.dumps() use double quotes?
JSON requires double quotes around string keys and string values.