The json.dump() function in Python is part of the json module, used to serialize Python objects into JSON format and write the output directly to a file-like object. T
his is particularly useful when you need to store data in a structured format for later retrieval or for data exchange between systems.
Syntax:
python
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
– obj`: The Python object to be serialized.
– fp: The file-like object where the JSON data will be written.
– indent: If specified, the output will be pretty-printed with the given number of spaces for indentation.
– sort_keys: If True, the output will have the dictionary keys sorted.
Example:
python
import json
data = {
“name”: “John Doe”,
“age”: 30,
“is_employee”: True,
“skills”: [“Python”, “Django”, “Machine Learning”]
}
with open(‘data.json’, ‘w’) as file:
json.dump(data, file, indent=4)
This example writes the data dictionary to data.json in a readable format with 4-space indentation.
json.dump() is essential for working with JSON files, enabling efficient data storage and sharing in applications.