How to Write JSON Data in Python 


               


How to Write JSON Data in Python



Python


In this article, we show how to write JSON data in Python.

JSON data and Python data look almost identical.

This is a subtle difference but an important one, since you should not send Python-formatted data to a JSON file.

So, to encode data in JSON, or write JSON data, you take the dictionary in Python and encode it with the json.dumps() function.

The json_dumps() function will convert a dictionary in Python to data in JSON format.

When you convert a dictionary to JSON data with the json_dumps() function, the data type will change from type dict to type str.

So, below we create a dictionary in Python and encode this to JSON format.



So, the first thing we must do is import the json module.

We then create a dictionary called person. This dictionary contains name, age, and race attributes.

This is Python data in the form of a dictionary.

To make this data JSON data, we use the json_dumps() function and input as the parameter the Python dictionary data. This encodes the Python data to JSON data. We save this in the variable json_string.

If you were to now get the data type of json_string, you would now see that the data is of type string (str). It is no longer a dictionary.

And this is how you can write, or encode, JSON data from Python data.


Related Resources

How to Parse JSON Data in Python



HTML Comment Box is loading comments...