json.dump() is a method in Python's json module used to serialize a Python object into JSON format and write it directly to a file. It is commonly used for saving data to disk in a structured, human-readable format.
Key Features:
Purpose: Writes JSON data to a file (e.g.,
data.json).Syntax:
json.dump(obj, file, indent=None, sort_keys=False, ensure_ascii=True, ...)Parameters:
obj: The Python object (dict, list, etc.) to convert.file: A file object opened in write mode ('w'or'wb').indent: Adds whitespace for readable (pretty-printed) output (e.g.,indent=4).sort_keys: IfTrue, sorts dictionary keys alphabetically.ensure_ascii: IfFalse, allows non-ASCII characters (e.g.,é,中文) to be written as-is.
Example:
import json
data = {"name": "Alice", "age": 30, "city": "New York"}
with open("data.json", "w") as f:
json.dump(data, f, indent=4)Output (in data.json):
{
"name": "Alice",
"age": 30,
"city": "New York"
}Difference from json.dumps():
json.dump()→ writes to a file.json.dumps()→ returns a JSON string (useful for printing, logging, or sending over a network).
Use json.dump() when you need to save structured data persistently.
python - How do I write JSON data to a file? - Stack Overflow
Python json dump - Stack Overflow
json.dump with python.dump
`jsonable_encoder(obj)` vs `obj.model_dump(mode='json')`
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.
data is a Python dictionary. It needs to be encoded as JSON before writing.
Use this for maximum compatibility (Python 2 and 3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
See json documentation.
To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
The code is simpler in Python 3:
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
On Windows, the encoding='utf-8' argument to open is still necessary.
To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
The codecs.getwriter call is redundant in Python 3 but required for Python 2
Readability and size:
The use of ensure_ascii=False gives better readability and smaller size:
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.
The last % is the first character of your console prompt line or a feature of your shell (https://unix.stackexchange.com/questions/167582/why-zsh-ends-a-line-with-a-highlighted-percent-symbol)
Nothing to do with json, nor python.
Because, when print() add a '\n' at the end, the dump to stdout doesn't
The reason is that print(json.dumps(data, indent=4)) prints a newline, and json.dump(data, sys.stdout, indent=4) does not.
You can try adding a print() at the end:
Copyprint(50*'-')
print(json.dumps(data, indent=4))
print(50*'-')
json.dump(data, sys.stdout, indent=4)
print()
Is the % symbol part of your shell's prompt?
When you do json.dump you can pass data into the function and where to put it, and it creates a new json file. How could I do this but have the language be python when it dumps? I need to do this because json does not read tuples and other things I am wanting to save into the file. Thanks