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.
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
importjsondata={"emp1":{"name":"Lisa","age":34,"salary":54000},"emp2":{"name":"Elis","age":24,"salary":40000},}# Writing to a JSON file with indentationwithopen("output.json","w")asoutfile: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
importjsondata={("address","street"):"Brigade Road"}# Tuple as key# Writing to a JSON file with skipkeys=Truewithopen("output.json","w")asoutfile: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
importjsondata={"greeting":"¡Hola Mundo!"}# Writing to a JSON file with ensure_ascii=False to preserve non-ASCII characterswithopen("output.json","w",encoding="utf8")asoutfile: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
importjsondata={"value":float("nan"),"infinity":float("inf")}# Writing to a JSON file with allow_nan=Truewithopen("output.json","w")asoutfile: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
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.