Serializing JSON data in Python
Serialization is the process of encoding the from naive datat type to JSON format. The Python module json converts a Python dictionary object into JSON object, and list and tuple are converted into JSON array, and int and float converted as JSON number, None converted as JSON null.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Let’s take a look at how we serialize Python data to JSON format with these methods:
- Dump().
- Dumps().
json.dump()
json.dump() method can be used for writing to JSON file. Write data to a file-like object in json format.
Syntax: json.dump(dict, file_pointer)
Parameters:
- dictionary – name of dictionary which should be converted to JSON object.
- file pointer – pointer of the file opened in write or append mode.
Below is the implementation:
Converting python object and writing into json file.
Python3
# import moduleimport json # Data to be writtendata = { "user": { "name": "satyam kumar", "age": 21, "Place": "Patna", "Blood group": "O+" }} # Serializing json and # Writing json filewith open( "datafile.json" , "w" ) as write: json.dump( data , write ) |
Output:
data_file.json
json.dumps()
json.dumps() method can convert a Python object into a JSON string.
Syntax: json.dumps(dict)
Parameters:
- dictionary – name of dictionary which should be converted to JSON object.
Below is the implementation:
Converting python object into json string.
Python3
# import moduleimport json # Data to be written data = { "user": { "name": "satyam kumar", "age": 21, "Place": "Patna", "Blood group": "O+" }} # Serializing jsonres = json.dumps( data )print( res ) |
Output:

