how to convert a list of object to json format in python
You should code a dump
method in your object and use it when sending things to json module:
class IpPort:
def __init__(self, ip, port, time, status):
self.ip = ip
self.port = port
self.time = time
self.status = status
def dump(self):
return {"IpPortList": {'ip': self.ip,
'port': self.port,
'time': self.time,
'status': self.status}}
And when converting data to json:
json.dumps([o.dump() for o in my_list_of_ipport])
You can even make it more automatic by creating a custom encoder for your JSON but it seems like overkill here.
Edit:
To answer the comment on the load part, if you just want a list of dict json.loads
is the way to go. If you want a list of IpPort
you have to ways to do it, either you do the following (considering that your dumped dicts are flat):
ip_ports = [IpPort(**attrs) for attrs in json.loads(dumped_ipports)]
Note: The **
operator transform a dict into keyword arguments.
If your dumped dicts are not flat (which is your case), you should create a static method load
which returns an instance of the object created from a dump:
class IpPort:
... blablabla ...
@staticmethod
def load(dumped_obj):
return IpPort(dumped_obj['IpPortList']['ip'],
dumped_obj['IpPortList']['port'],
dumped_obj['IpPortList']['time'],
dumped_obj['IpPortList']['status'])
And the way to make it a list:
my_ip_ports = [IpPort.load(dumped_ipport)
for dumped_ipport in json.loads(dumped_stuff)]
akinKaplanoglu
Updated on June 14, 2022Comments
-
akinKaplanoglu almost 2 years
I have a
class
in python. And I made a list that contains thisclass
instances. I want to convert this list to json. Here is myclass
class IpPort: def __init__(self,ip,port,time,status): self.ip=ip self.port=port self.time=time self.status=status
And I have a
list of
thisobject
. I want to convert thislist
tojson
format to send asocket
. But I could not. How can I do this? I want it to be like:{"IpPortList":{[]}}
EDIT Here is my code for this.But it did not work:
li=list() i1=IpPort("kk",12,None,"w") i2=IpPort("kk",15,None,"s") li.append(i1) li.append(i2) jsons= json.dumps(li) s.send(jsons)
And i want to send this json to a socket.After that i want to take the json at the other side.In the other side again i want to convert it to list.
-
akinKaplanoglu over 9 yearsThank You very [email protected] can i take the json object in other side?And i want to convert it to list again .
-
Benoît Latinier over 9 yearsEdited to add load part.