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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read