Santhosh
Santhosh

Reputation: 11768

python json.dumps: unable to ignore non serializable objects

In python when i want to pretty print an object during debugging i use

print(json.dumps(obj.__dict__), indent=4, sort_keys=True)

because just using print(obj) is not very readable

Then if some of the items are non serialzable it says

Object of type SOMETHING is not JSON serializable

So my goal is to just check an object while debugging and not to have a perfectly serialized object to pass it and later convert back.

I tried the following by adding default=str to avoid the error and it worked in many cases

print(json.dumps(obj.__dict__), indent=4, sort_keys=True, default=str)

But still in some cases it shows

Object of type SOMETHING is not JSON serializable

So how to solve this.

The object i am trying is from Django project. I am trying to pretty print using the help of json.dumps

from django.db import connections
import json
for c in connections.all():
    c_dict = {k: getattr(c, k) for k in dir(c)} # this gives all the properties listed using dir(c)
    print(json.dumps(c_dict), indent=4, sort_keys=True, default=str)

ANSWER:

@milanbalanz answered it in the comments. Its a typo error of the brackets. So default=str works as its indented to the wrong one is

print(json.dumps(c_dict), indent=4, sort_keys=True, default=str)

the right one is

print(json.dumps(c_dict, indent=4, sort_keys=True, default=str))

Upvotes: 2

Views: 3319

Answers (2)

milanbalazs
milanbalazs

Reputation: 5329

The position of your parentheses are not correct.

The correct line:

print(json.dumps(obj.__dict__, indent=4, sort_keys=True, default=str))

Upvotes: 6

Shishir Naresh
Shishir Naresh

Reputation: 763

Try the below code, Hope this would help.

from json import JSONEncoder

class Encoder(JSONEncoder):
        def default(self, o):
            return o.__dict__ 

Encoder().encode(f)

Upvotes: 1

Related Questions