json.dump() method in Python is used to serialize a Python object into a JSON formatted string and write it directly into a file. This method is part of the built-in json module, which is useful when you need to save Python data structures like dictionaries or lists in JSON format.
Syntax
json.dump(obj, file, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None)
Parameters:
- obj: The Python object (e.g., dictionary, list) to convert to JSON.
- file: The file-like object where the JSON data will be written.
- skipkeys: If True, non-serializable keys will be ignored. Default is False.
- ensure_ascii: If True, all non-ASCII characters are escaped. If False, non-ASCII characters are written as-is. Default is True.
- check_circular: If True, checks for circular references. Default is True.
- allow_nan: If True, allows NaN, Infinity, and -Infinity values in JSON. Default is True.
- cls: A custom JSON encoder class. Default is None.
- indent: Specifies the number of spaces for indentation to improve readability. Default is None.
- separators: A tuple that defines how the items in the JSON file will be separated. Default is (', ', ': ').
Let's look at some examples:
Example 1: Writing JSON Data to a File with Indentation
In this example, we will demonstrate how to write Python data to a JSON file while formatting it with indentation for better readability.
Python
import json
data = {
"emp1": {"name": "Lisa", "age": 34, "salary": 54000},
"emp2": {"name": "Elis", "age": 24, "salary": 40000},
}
# Writing to a JSON file with indentation
with open("output.json", "w") as outfile:
json.dump(data, outfile, indent=4)
Output:
json.dump()
Example 2: Using skipkeys to Ignore Non-Serializable Keys
This example demonstrates how to use the skipkeys parameter to prevent errors when attempting to serialize non-serializable keys, like tuples.
Python
import json
data = {("address", "street"): "Brigade Road"} # Tuple as key
# Writing to a JSON file with skipkeys=True
with open("output.json", "w") as outfile:
json.dump(data, outfile, skipkeys=True)
Output:
{}
In the above example, the tuple ("address", "street") is ignored because it's not serializable, and no error is raised due to skipkeys=True.
Example 3: Writing Non-ASCII Characters
Here, we will demonstrate how to handle non-ASCII characters in the JSON output by setting ensure_ascii=False.
Python
import json
data = {"greeting": "¡Hola Mundo!"}
# Writing to a JSON file with ensure_ascii=False to preserve non-ASCII characters
with open("output.json", "w", encoding="utf8") as outfile:
json.dump(data, outfile, ensure_ascii=False)
Output:
{
"greeting": "¡Hola Mundo!"
}
With ensure_ascii=False, the special characters are written as-is without being escaped.
Example 4: Writing JSON with NaN and Infinity Values
This example shows how to handle special floating-point values like NaN and Infinity by adjusting the allow_nan parameter.
Python
import json
data = {"value": float("nan"), "infinity": float("inf")}
# Writing to a JSON file with allow_nan=True
with open("output.json", "w") as outfile:
json.dump(data, outfile, allow_nan=True)
Output:
{
"value": NaN,
"infinity": Infinity
}
By setting allow_nan=True, we can serialize special float values like NaN and Infinity.
Difference between dump() and dumps()
dump() | dumps() |
---|
The dump() method is used when the Python objects have to be stored in a file. | The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . |
The dump() needs the json file name in which the output has to be stored as an argument. | The dumps() does not require any such file name to be passed. |
This method writes in the memory and then command for writing to disk is executed separately | This method directly writes to the json file |
Faster method | 2 times slower |
Similar Reads
json.dumps() in Python json.dumps() is a function in Pythonâs json module that converts a Python object into a JSON formatted string. It allows you to serialize Python objects such as dictionaries, lists, and more into JSON format.Syntaxjson.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True
5 min read
json.load() in Python json.load() function in Python is used to read a JSON file and convert it into a Python object, such as a dictionary or a list. JSON (JavaScript Object Notation) represents data as key/value pairs, where keys are strings and values can be different JSON data types.Syntaxjson.load(file_object)Paramet
3 min read
JSON Formatting in Python JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate. Python Format JSON Javascript Object Notation abbreviated as JSON is a
3 min read
Python JSON Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called JSON. This package provides all the necessary tools for working with JSON Objects i
3 min read
json.loads() in Python JSON is a lightweight data format used for storing and exchanging data across systems. Python provides a built-in module called json to work with JSON data easily. The json.loads() method of JSON module is used to parse a valid JSON string and convert it into a Python dictionary. For example:Pythoni
4 min read
How to JSON decode in Python? When working with JSON data in Python, we often need to convert it into native Python objects. This process is known as decoding or deserializing. The json module in Python provides several functions to work with JSON data, and one of the essential tools is the json.JSONDecoder() method. This method
5 min read