Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将小数转换为JSON的Python dict_Python_Json - Fatal编程技术网

将小数转换为JSON的Python dict

将小数转换为JSON的Python dict,python,json,Python,Json,可能重复: 任务:将包含混合数据类型(integer/strint/decimal/…)作为值的dict转换为JSON数组 我知道如何将python dict转换为JSON: D = {key1:val1, key2,val2} import json jD = json.dumps(D) 我还知道十进制值必须转换成字符串,否则python将抛出“decimal不可json序列化”的错误 所以我需要遍历dict来查找数据类型 for key in D.keys(): if type(

可能重复:

任务:将包含混合数据类型(integer/strint/decimal/…)作为值的dict转换为JSON数组

我知道如何将python dict转换为JSON:

D = {key1:val1, key2,val2}
import json
jD = json.dumps(D)
我还知道十进制值必须转换成字符串,否则python将抛出“decimal不可json序列化”的错误

所以我需要遍历dict来查找数据类型

for key in D.keys():
    if type(key) == '<class "decimal.Decimal">': ## this is erroneous. pl. suggest correction
    D[key] = str(D[key])
用于D.keys()中的键:
如果类型(键)='':##这是错误的。建议改正
D[key]=str(D[key])
但这种编程涉及手工编码和硬编码

如果我得到一个嵌套的字典结构,同样需要硬编码(这是错误的)


从dict中的任何数据类型获取JSON数组还有其他方法/技巧吗?

为什么不将JSONEncoder子类化?它既简单又干净:

class DecimalEncoder(json.JSONEncoder):
    def _iterencode(self, o, markers=None):

        if isinstance(o, decimal.Decimal):  # isinstance() is better than type(), because it handles inheritance
            return (str(o) for o in [o])

        return super(DecimalEncoder, self)._iterencode(o, markers)

请注意,JSON不能表示小数,只能表示浮点和字符串。因此,您应该将小数转换为字符串,如下所示:

keys_for_json = {str(k):v for k,v in keys.items()}

试试类型(key)。\uuuu name\uuuu related:你不能基于这个键转换数据类型吗?@JMAx,在使用simplejson.dumps和as_decimal=True之后,我得到了正确的json。谢谢。@Cez,键入(键)。\uuuuuuuuuu名字\uuuuuuuuuuu有效。谢谢。我正在寻找一种不需要手工操作的方法@JMax建议使用as_decimal=True的simplejson.dumps。这可以工作,但会将json对象括在方括号[]中。有没有办法避免这种情况?谢谢。@Vinet:你在这里写的问题已经结束了。如果您仍有任何问题(仍包含在括号中?),请随时询问新问题,并提供所有必要的信息。Pl。请参阅我对“Secator的回答”的评论。谢谢,比塞卡托的回答好