json.dump() is a built-in function from json module that is used to encode Python objects as JSON strings and write them to a file-like object. You can easily write JSON data to a file using the dump() function. In this article, I will explain json. dump() and using its syntax, parameters, and usage how we can store and transfer Python objects into a file in the form of JSON object.
1. What is JSON Data?
JSON (JavaScript Object Notation) is a format used to represent data in a way that is easy for both humans and machines to understand. It is commonly used to transmit data between web applications and servers. JSON is based on a subset of the JavaScript programming language, so if you’re familiar with JavaScript, you’ll find JSON easy to understand.
In JSON, data is represented using a simple key-value pair structure. The keys represent the names of fields or attributes of the data, while the values represent the actual data itself. JSON data can be represented as a string and can be easily converted to a Python dictionary or list using the built-in json module.
2. json.dump() Function
The dump() function is used to write JSON data to a file in Python. It takes two arguments, the data to be written, and the file object to write to. The syntax of the json.dump() function is given below.
Note that json.dump() only serializes basic Python data types like strings, numbers, booleans, lists, and dictionaries. If you have more complex objects like custom classes, you may need to write a custom encoder to handle them.
2.1 Syntax of json.dump() Function
Following is the syntax of json.dump() function
# Syntax of dump() function
json.dump(object, output, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separator=None)
2.2 Parameters
Following are the parameters of the dump() function.
data : (required) Any object, which is to be dumped into the file in JSON format.
file_object: (required) Where to write the JSON data.
indent: (optional)It is used to improve the readability of the data dumped into the JSON file. We can provide double quotes(” “) and integer values as its values. The double quotes(” “) make the key-value pairs appear in the new line.
skipkeys : (optional)The skipkeys parameter is used to tackle the key error generated during the dumping of data. If the key is not any of the standards-allowed types like int, float, string, None, or bool, the Python interpreter will raise an error so we must set the skipkeys parameter to True.
separator : (optional)The separator takes either one or two values. Now, the first value of the separator parameter tells the Python interpreter about the symbol that will separate one key-value pair from another. On the other hand, the second parameter is used to specify the separator that will separate the key from its value.
sort_keys :(optional) The sort_keys parameter can also take two values (boolean values True or False). So, if the parameter’s value is set to True then the keys are set in ascending order, on the other hand, if the parameter’s value is set to False then they are set in the same order as it was in the original Python object.
ensure_ascii:(optional) The ensure_ascii parameter can also take two values (boolean values True or False). The default value of the ensure_ascii parameter is set to True. Now, if the parameter’s value is set to False then the non-ASCII characters of the Python object are dumped into the output file as it is in the Python object.
allow_nan : (optional) A Boolean value specifying whether to allow NaN, Infinity, and -Infinity values. The default is True.
check_circular: A Boolean value specifying whether to check for circular references in the Python object. The default is True.
cls: A custom encoder class used to convert non-JSON serializable objects into JSON serializable objects.
2.3 Return Value
It returns a file containing a string object.
3. Using json.dump() to Write JSON Data to a File in Python
Let’s see an example of writing a Python object to a JSON file. The data parameter represents the JSON data to be written to the file. This can be any Python object that is JSON serializable, such as a dictionary or a list. Alternatively, you can also put this data into a file and read json from a file into an object.
Following is the syntax of writing JSON data to afile.
# Syntax of write JSON data to file
import json
with open(“data.json”, “w”) as outfile:
# json_data refers to the above JSON
json.dump(json_data, outfile)
where:
json_data is the Python object to be encoded as JSON.
“data.json” is the name of the file where the JSON data will be written.
“w” specifies that the file will be opened in write mode.
outfile is the file-like object where the JSON data will be written.
Here, in the below example json_data is a dictionary object which I will write to a file.
# Import json module
import json
# Create dictionary object which is json representation
json_data = {
“name”: “Python”,
“year”: 1991,
“creator”: “Guido van Rossum”,
“popular”: True
}
# Writing JSON data to a file using a file object
with open(“data.json”, “w”) as outfile:
# json_data refers to the above JSON
json.dump(json_data, outfile)
As you can see from the above, the JSON file has been returned from JSON data. When we want to see the JSON data on the console you can use json.dumps() function. It will return the JSON data from the Python object.
3.1 skipkeys Parameter of json.dump() in Python
The skipkeys parameter is a boolean value that determines whether keys that are not JSON serializable should be skipped (True) or raise a TypeError (False). The default value is False.
Let’s make the skipkeys value True and see the result.
import json
data ={
“name”: “Python”,
(1, 2): 1991,
“creator”: “Guido van Rossum”,
“popular”: True
}
# Example with skipkeys=True
with open(“data.json”, “w”) as outfile:
json.dump(data, outfile, skipkeys=True)
Yields the below output, because the JSON object is not serializable.
raise TypeError(f’keys must be str, int, float, bool or None, ‘
TypeError: keys must be str, int, float, bool or None, not tuple
3.2 “ensure_ascii” Parameter of json.dump()
The ensure_ascii parameter is a boolean value that determines whether non-ASCII characters should be escaped (False) or represented as ASCII characters (True). The default value is True.
import json
data = {“name”: “John”, “age”: 30, “city”: “New York”}
# Example with ensure_ascii=True (default)
with open(“data.json”, “w”) as outfile:
json.dump(data, outfile)
4. Conclusion
In this article, I will explain Python json.dump() function and using its syntax, parameters, and usage how we can write the JSON data to a file with examples.
Happy learning!!
json.dump() is a built-in function from json module that is used to encode Python objects as JSON strings and write them to a file-like object. You can easily write JSON data to a file using the dump() function. In this article, I will explain json. dump() and using its syntax, parameters, and usage how we Read More Python, Python Tutorial, Pending review by admin, Python JSON Examples