Converting a Python object to JSON allows the object's data to be stored or transmitted as text, so that it can be, for example, sent over an http session, and then converted back into an object. There's any number of ways to do this, but JSON is an accepted standard format that is supported by many languages.
The code shown here defines a very simple object class, a vm (virtual machine), that includes name and state attributes and a list of disks. My class isn't very useful as it is, but the idea is to show that we can handle both simple string as well as list attributes.
The code creates a few vm objects and stores them in a list. Then, a list is created using the vm objects' dictionaries. The dictionaries themselves are very close to JSON as it is, but not quite in formal JSON, so the json.dumps method is used to get the data into JSON format.
Finally, the JSON data is converted back into vm objects using the json.loads method. The object_hook tells json.loads to use the as_vm function to recreate the objects.
import json
#class definition for vm object class vm: def __init__(self,name,state): self.disk=[] self.name=name self.state=state def addDisk(self,d): self.disk.append(d)
#function to create a vm object from serialized dictionary data def as_vm(vmdict): newvm=vm(vmdict['name'],vmdict['state']) for d in vmdict['disk']: newvm.addDisk(d) return newvm
#create some VMs and add them to a list vmlist= [] myvm=vm('server1','running') myvm.addDisk(1000) myvm.addDisk(2500) vmlist.append(myvm)
myvm=vm('server2','stopped') myvm.addDisk(500) myvm.addDisk(2000) vmlist.append(myvm)
#show vm info for myvm in vmlist: print myvm.name + " - " + myvm.state + " - disks: " + str(myvm.disk)
#create list of vm dictionaries vmdictlist= [] for myvm in vmlist: vmdictlist.append(myvm.__dict__)
#convert dictionary list to json jsondata=json.dumps(vmdictlist) print "objects serialized: " + jsondata
#later - convert json into vm objects again newvmlist=json.loads(jsondata, object_hook=as_vm)
#show vm info for myvm in newvmlist: print myvm.name + " - " + myvm.state + " - disks: " + str(myvm.disk)
0 comments:
Post a Comment