How to make a class JSON Serializable in Python?

Object Oriented ProgrammingProgrammingPython

Serialisation is the process of transforming objects of complex data types to native data types so that they can then be easily converted to JSON notation. 

If you have a JSON string, you can convert it into a JSON string by using the json.dumps() method.

Python pickle module is used for serialising and deserialising a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serialises” the object first before writing it to file. Pickling is a way to convert a python object (i.e) list, dict, etc... into a character stream. 

Example

import json
x = {
   "name": "Archana",
   "age": 30,
   "city": "Hyderabad"
   }
# convert into JSON String by using json.dumps():
y = json.dumps(x)
print(y)

Output

{"name": "Archana", "age": 30, "city": "Hyderabad"}

Example 2

import json
Emp = {1:"Archana",
       2:"Krishna",
       3:"Vineeth",
       4:"Ramesh"}
jsonString = json.dumps(Emp)
print(jsonString)
Empid = [71,72,73,74]
jsonString = json.dumps(Empid)
print(jsonString)

Output

{"1": "Archana", "2": "Krishna", "3": "Vineeth", "4": "Ramesh"}
[71, 72, 73, 74]
raja
Sri
Published on 26-Jun-2019 19:20:44
Advertisements