-1

I am creating one Response Model in python in which one of the property is assigned value as lets say 23.12.I am using the following code to convert respone model to json object .

orders.append(json.dumps(json.dumps(response, default=obj_dict)))

where obj_dict is defined like this :

def obj_dict(obj):
    if isinstance(obj,decimal.Decimal):
        return obj
    return obj.__dict__

As decimal does not have dict property so thought of parsing the value above and returning the obj but getting the following error:

ValueError: Circular reference detected

1

1 Answer 1

0

json.dumps traverses the dictionary, and for every object it cannot serialise it passes it to the function provided as the default argument.

This is how your serializer should look like:

def dec_serializer(o):
    if isinstance(o, decimal.Decimal):
        # if current object is an instance of the Decimal Class, 
        # return a float version of it which json can serialize 
        return float(o)

You current code says,

def obj_dict(obj):
    if isinstance(obj,decimal.Decimal):
        # If obj is an instance of Decimal class return it
        # Which is basically returning whatever is coming
        return obj
    # and for all other types of objects return their dunder dicts 
    return obj.__dict__
Sign up to request clarification or add additional context in comments.

Comments

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.