-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

divyanayan awasthi
  • 890
  • 1
  • 8
  • 33
  • Possible duplicate of [Serializing output to JSON - ValueError: Circular reference detected](https://stackoverflow.com/questions/14249115/serializing-output-to-json-valueerror-circular-reference-detected) – Azat Ibrakov Apr 17 '19 at 11:04

1 Answers1

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__
Shuvojit
  • 1,390
  • 8
  • 16