Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

make Python class serializable

import json

class Employee:
    def __init__(self, name, salary, address):
        self.name = name
        self.salary = salary
        self.address = address

    def toJson(self):
        return json.dumps(self, default=lambda o: o.__dict__)

class Address:
    def __init__(self, city, street, pin):
        self.city = city
        self.street = street
        self.pin = pin

address = Address("Alpharetta", "7258 Spring Street", "30004")
employee = Employee("John", 9000, address)

print("Encode into JSON formatted Data")
employeeJSONData = json.dumps(employee.toJson(), indent=4)
print(employeeJSONData)

# Let's load it using the load method to check if we can decode it or not.
print("Decode JSON formatted Data")
employeeJSON = json.loads(employeeJSONData)
print(employeeJSON)
Comment

PREVIOUS NEXT
Code Example
Python :: timedelta format python 
Python :: class decorator python 
Python :: change part of a text file python 
Python :: python replace list from another dictionary items 
Python :: how to make loops in python 
Python :: sum of even numbers 
Python :: giving number of letter in python 
Python :: determinant of 3x3 numpy 
Python :: python version of settimout 
Python :: upgrade python version windows 
Python :: check if a value is in index pandas dataframe 
Python :: import gpio raspberry pi 
Python :: download button image streamlit 
Python :: python docstring 
Python :: python remove the element in list 
Python :: Accessing elements from a Python Dictionary using the get method 
Python :: how to index lists in python 
Python :: python map 
Python :: python multidimensional dictionary 
Python :: list add pythhon 
Python :: django pytest how to load data 
Python :: how to get the time zones in python 
Python :: variable referenced before assignment python 
Python :: sessions in flask 
Python :: print variable python 
Python :: how to create list in python 
Python :: turn numpy function into tensorflow 
Python :: Example 1: Reset Index & Drop Old Index pandas 
Python :: problem solving with python 
Python :: drop variable pandas 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =