1

I'm trying to run the json.dumps method on a nested class/object and it fails on TypeError: <__main__.nested_object object at 0x...> is not JSON serializable

What should I change in my class so I could call json.dumps method with input parameters of an implementation of JSONEncoder?

Here is a very simple code that simulate the problem:

class leaf_object(object):
    def __init__(self, s):
        self.value = s

class nested_object(object):
    def __init__(self, a, b_list):
        self.a = a
        self.b_list = b_list

if __name__ == "__main__":
    obj = nested_object('a1', [leaf_object('a1.1'),leaf_object('a1.2')])
    import json
    print(json.dumps(obj))
2
  • 2
    It doesn't matter if an object is nested or not; to encode any object that isn't directly mapped to a JSON type you'll need to write additional code to handle the conversion. Commented Aug 21, 2014 at 11:15
  • Ok, which code is it? I prefer it will be a method I need ti implement in the object and outside it because I have another place that calls json,dumps on any object it gets Commented Aug 21, 2014 at 11:30

1 Answer 1

0

You can use subclass JSONEncoder and implement your own custom serialization.so use this code :

from json import JSONEncoder

class leaf_object(object):
    def __init__(self, s):
        self.value = s

class nested_object(object):
    def __init__(self, a, b_list):
        self.a = a
        self.b_list = b_list

class MyEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__
if __name__ == "__main__":
    obj = nested_object('a1', [leaf_object('a1.1'),leaf_object('a1.2')])
    obj=MyEncoder().encode(obj)
    import json
    print(json.dumps(obj))

this is the result:

"{\"a\": \"a1\", \"b_list\": [{\"value\": \"a1.1\"}, {\"value\": \"a1.2\"}]}"
Sign up to request clarification or add additional context in comments.

2 Comments

I wasn't clear - I'm trying to avoid the changing of the json.dumps by changing the nested/leaf_object objects code BTW, you can in your suggestion you can use the json dumps tis way : print(json.dumps(obj,cls=MyEncoder))
why you dont want to change json.dump ? so you can change the obj before, as i update the answer ?... if you want another ways you can see similar questions !

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.