Lokesh Jinka
Lokesh Jinka

Reputation: 7

How to convert Class Object to JSON in Python

import json

class Abc:

    firstName = ''
    secondName = ''

obj = Abc()

obj.firstName = 'Raj'

res = json.dumps(obj, default=lambda o: o.__dict__)

print(res)

Output: {"firstName": "Raj"}

But I need the Output like this

{"firstName": "Raj", "secondName": ""}

Any Solution for this??

Upvotes: 0

Views: 2144

Answers (1)

chepner
chepner

Reputation: 531165

First, start with a proper class definition.

class Abc:
    def __init__(self, first='', second=''):
        self.firstName = first
        self.secondName = second

Then define an appropriate JSONEncoder subclass:

import json


class AbcEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Abc):
            return {"firstName": obj.firstName, "secondName": obj.secondName}
        return super().default(obj)


obj = Abc("Raj")
res = json.dumps(obj, cls=AbcEncoder)

Upvotes: 1

Related Questions