dump() v/s dumps() in JSON module of Python

·

2 min read

Hello folks! I recently started my Python journey and came across Python's JSON module while working on a project. I encountered two functions : json.dump() and json.dumps() which look similar and hence confused me a lot. After some research and playing around with the two functions, I finally got a clear idea. So I thought of sharing my learnings regarding it in today's article.

What's common in them?

Both json.dump() and json.dumps() serialize python objects into JSON format, but they are used in different contexts. So, let's talk about the differences between them.

What does json.dump() do?

The json.dump() method serializes a python object into JSON and writes it directly to a file-like object. It does not return a string but writes the JSON data directly to a file.

Let's understand this by an example.

In the image above, the data variable is the python object that contains the data in JSON-compatible format. We want to write this data into the sample_data.json file, which is empty now. We will open the sample_data.json file in writing mode and use the json.dump() method to write data into the file. The json.dump() takes two parameters : a python object containing data in JSON-compatible format and the file object into which the data is to be written.

Now let's look at the output (the sample_data.json file) after running this python script.

Here we go! Our data has been written into the sample_data.json file successfully.

Now let's talk about json.dump() method.

What does json.dumps() do?

The json.dumps() method serializes a python object into a JSON string. The 's' in dumps() stands for "string".

Let's understand this by an example.

In the image above, the data variable is the python object that contains the data in JSON-compatible format. We want to serialize this data into JSON string. So, we will use the json.dumps() method for it. The json.dumps() method takes only one argument : the python object containing data in JSON-compatible format. It will convert it into a JSON string and return us the string. We have stored this string into the json_string variable.

Now let's look at the output.

In the image above, we can see that the json_string variable contains a string which represents our python object (which contained data in JSON compatible format).

Summary

Both json.dump() and json.dumps() are functions from Python's JSON module used to serialize Python objects into JSON format. The primary difference is that `json.dump()` writes the serialized JSON data directly to a file, while `json.dumps()` returns the serialized JSON data as a string.

Hope you found this article on json.dump() vs json.dumps() helpful. Happy coding😄!