0
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??

3
  • 1
    Try giving the class a constructor and create as member fields. Ex: this.firstName = '' and this.secondName = '' Commented May 20, 2021 at 13:55
  • Does this answer your question? How to make a class JSON serializable Commented May 20, 2021 at 13:58
  • For simple classes only containing data and no interface, you might be interested in checking the dataclasses. Commented May 20, 2021 at 13:59

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

7 Comments

Not your downvoter, but if I were to, it would be because there's a duplicate for this question and answer already
I cannot use this AbcEncoder method because in my program class contains 30 variables........ I gave simple question to understand the problem
I don't see how the number of variables is relevant.
@Civs Fair enough, though I think the class definition needed pointing out. (For example, one of the answers in the dupe suggests passing the instance's __dict__ attribute to json.dumps, but that won't apply since secondName in the original code is a class attribute and won't be in obj.__dict__.)
(I kind of wish json supported __to_json__ and __from_json__ hooks that you could add to your classes, but I haven't really thought out what problems that might introduce.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.