Python list of objects to JSON | Example code

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

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 and suggestions on this Python List and JSON topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.