json.dumps() is a Python function that converts a Python object (like a dictionary, list, or string) into a JSON-formatted string. It is used when you need to serialize data for storage, transmission (e.g., over APIs), or further processing as text.
Key Features:
Returns a string: The output is a
strobject, not a file.Common use cases: Sending data to web APIs, saving structured data as text, or preparing data for logging.
Formatting options:
indent: Adds pretty-printing (e.g.,indent=2for 2-space indentation).sort_keys: Sorts dictionary keys alphabetically (e.g.,sort_keys=True).ensure_ascii: Controls whether non-ASCII characters are escaped (default:True).separators: Customizes separators between items and keys (e.g.,separators=(',', ':')).
Example:
import json
data = {"name": "Alice", "age": 30, "skills": ["Python", "SQL"]}
json_string = json.dumps(data, indent=2, sort_keys=True)
print(json_string)Output:
{
"age": 30,
"name": "Alice",
"skills": [
"Python",
"SQL"
]
}💡 Note: Use
json.dump()to write directly to a file.json.dumps()returns a string, which can then be written to a file manually if needed.
Videos
Hi, hope everyone is well.
Just nearing the basics end of PCC book, I'm at saving user's data now. What exactly is the reason, when storing simple data, to use json.dump() or load(), instead of just saving and then reading it from simple text file?
I just can't place it in my head why do I really need it and it always makes it more difficult for me to learn if that's the case.
Thank you all in advance.