【问题标题】:Retrieve decimal value and to create the json in python检索十进制值并在 python 中创建 json
【发布时间】:2019-09-07 14:36:38
【问题描述】:
我正在 python 中创建一个响应模型,其中一个属性被赋值,比如 23.12。我正在使用以下代码将响应模型转换为 json 对象。
orders.append(json.dumps(json.dumps(response, default=obj_dict)))
obj_dict 的定义如下:
def obj_dict(obj):
if isinstance(obj,decimal.Decimal):
return obj
return obj.__dict__
由于十进制没有 dict 属性,所以考虑解析上面的值并返回 obj 但得到以下错误:
ValueError:检测到循环引用
【问题讨论】:
标签:
python
json
python-3.x
【解决方案1】:
json.dumps 遍历字典,对于每个无法序列化的对象,它会将其传递给作为默认参数提供的函数。
你的序列化器应该是这样的:
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)
你当前的代码说,
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__