Skip to content

Python list of objects to JSON | Example code

  • by

You can use a list comprehension to produce a list of dictionaries, then convert that using json.dumps() function.

Convert Python list of objects to JSON example

A simple example codes a dump method in your object and uses it when sending things to json module:

import json


class IpPort:
    def __init__(self, ip, port, status):
        self.ip = ip
        self.port = port
        self.status = status

    def dump(self):
        return {"IpPortList": {'ip': self.ip,
                               'port': self.port,
                               'status': self.status}}


li = list()

i1 = IpPort("kk", 12, "w")
i2 = IpPort("kk", 15, "s")

li.append(i1)
li.append(i2)
print(type(li))

res = json.dumps([o.dump() for o in li], indent=3)
print(type(res))
print(res)

Output:

Python list of objects to JSON

Do comment if you have any doubts or suggestions on this Python List and JSON topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *