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

001
  • 13,291
  • 5
  • 35
  • 66
  • 1
    Try giving the class a constructor and create as member fields. Ex: `this.firstName = ''` and `this.secondName = ''` – 001 May 20 '21 at 13:55
  • Does this answer your question? [How to make a class JSON serializable](https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable) – C.Nivs May 20 '21 at 13:58
  • For simple classes only containing data and no interface, you might be interested in checking the [dataclasses](https://docs.python.org/3/library/dataclasses.html). – joubs May 20 '21 at 13:59

1 Answers1

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)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Not your downvoter, but if I were to, it would be because there's a duplicate for this question and answer already – C.Nivs May 20 '21 at 14:05
  • I cannot use this AbcEncoder method because in my program class contains 30 variables........ I gave simple question to understand the problem – Lokesh Jinka May 20 '21 at 14:06
  • 1
    I don't see how the number of variables is relevant. – chepner May 20 '21 at 14:11
  • 1
    @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__`.) – chepner May 20 '21 at 14:13
  • Is there an advantage to using a JSONEncoder subclass over a *stand-alone* function passed to the default parameter? – wwii May 20 '21 at 14:22
  • I don't think there's a *strong* advantage. I think each can do what the other does, just in a different fashion. For example, the `default` argument should either encode the object or raise a `TypeError`, while the method will probably use `super` to defer to another encoder. The function could call another function instead of raising an error, and the method could of course raise an error instead of using `super()`, so I think it's mostly a matter of preference for how to organize code. – chepner May 20 '21 at 14:30
  • 1
    (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.) – chepner May 20 '21 at 14:31