Site icon Spark By {Examples}

Python json.dump() Function

Python json dump

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.

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:

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!!

Exit mobile version