Serialization and Deserialization of JSON Object

Python and the JSON module work exceptionally well with dictionaries. For serializing and deserializing JSON objects in Python, you can utilize the “__dict__ “attribute available on many Python objects. 

This attribute is a dictionary used to store an object’s writable attributes. You can leverage this attribute effectively when working with JSON data, making the process seamless and efficient.

Code: 

Python3




import json
class GFG_User(object):
    def __init__(self, first_name: str, last_name: str):
        self.first_name = first_name
        self.last_name = last_name
         
user = GFG_User(first_name="Jake", last_name="Doyle")
json_data = json.dumps(user.__dict__)
print(json_data)
print(GFG_User(**json.loads(json_data)))


Output: 

{"first_name": "Jake", "last_name": "Doyle"} 
__main__.GFG_User object at 0x105ca7278

Note: The double asterisks ** in the GFG_User(**json.load(json_data) line may look confusing. But all it does is expand the dictionary.

Serialize and Deserialize complex JSON in Python

JSON stands for JavaScript Object Notation. It is a format that encodes the data in string format. JSON is language-independent and because of that, it is used for storing or transferring data in files. 

Serialization of JSON object: It means converting a Python object (typically a dictionary) into a JSON formatting string.

Deserialization of JSON object: It is just the opposite of serialization, meaning converting a JSON-formatted string back to a Python Object.

JSON Object is defined using curly braces{} and consists of a key-value pair. It is important to note that the JSON object key is a string and its value can be any primitive(e.g. int, string, null) or complex data type (e.g. array).

Example of JSON Object:

{
"id":101,
"company" : "w3wiki"
}

Complex JSON objects are those objects that contain a nested object inside the other. Example of Complex JSON Object.

{
"id":101,
"company" : "w3wiki",
"Topics" : { "Data Structure",
"Algorithm",
"Gate Topics" }
}

Similar Reads

Serialization and Deserialization of JSON Object

Python and the JSON module work exceptionally well with dictionaries. For serializing and deserializing JSON objects in Python, you can utilize the “__dict__ “attribute available on many Python objects....

Serialization and Deserialization of Complex JSON Objects

...