关于json.dumps的使用和解决Object of type XXX is not JSON serializable错误

2022-03-11 17:21:33 浏览数 (1)

JSON是一种轻量级的数据交换格式。采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

json.dumps() 是把python对象转换成json对象的一个过程,生成的是字符串。

MyEncoder来自网上,将numpy的数据类型进行转换。

代码语言:javascript复制
import numpy as np
import json

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(MyEncoder, self).default(obj)

初始化数据,通过numpy构造随机数

代码语言:javascript复制
# 初始化数据
monthstr=[str(x) '月' for x in range(1, 13)]
# ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
nphigh= np.random.randint(20,35,size=12)
# [21 32 30 27 34 25 27 30 26 22 30 22]
nplow=np.random.randint(5,20,size=12)
# [19  9 17  8 14  9 18 19  8 11  6  9]

Object of type ndarray is not JSON serializable错误以及解决办法

代码语言:javascript复制
# ---------------error  TypeError: Object of type ndarray is not JSON serializable--------------
# json.dumps({'month':monthstr,'high':nphigh,'low':nplow})
# ---------------solution 对np.integer,np.floating,np.ndarray进行转码
json.dumps({'month':monthstr,'high':nphigh,'low':nplow},cls=MyEncoder)
# {"month": ["1u6708", "2u6708", "3u6708", "4u6708", "5u6708", "6u6708", "7u6708", "8u6708", "9u6708", "10u6708", "11u6708", "12u6708"],
# "high": [32, 27, 28, 23, 24, 26, 29, 25, 24, 21, 31, 27],
# "low": [6, 17, 17, 6, 9, 15, 14, 18, 13, 11, 6, 5]}
# -----------------------------------------------------------------------------------------------

Object of type int32 is not JSON serializable错误以及解决办法,这里用到list()和tolist()方法,可以看出两者还是有明显不同。

# list()将外层转化为list类型,内层数据类型还是原始类型。

# tolist()方法将外层内层全转化为list类型。

代码语言:javascript复制
# ---------------------------list()和tolist()差异化---------------------------------------------
# list()将外层转化为list类型,内层数据类型还是原始类型。
# tolist()方法将外层内层全转化为list类型。
high= list(nphigh)
low=list(nplow)

# # ---------------error  TypeError: Object of type int32 is not JSON serializable--------------
# json.dumps({'month':monthstr,'high':high,'low':low})
# TypeError: Object of type int32 is not JSON serializable
# ---------------solution 对np.integer,np.floating,np.ndarray进行转码
json.dumps({'month':monthstr,'high':high,'low':low},cls=MyEncoder)
# {"month": ["1u6708", "2u6708", "3u6708", "4u6708", "5u6708", "6u6708", "7u6708", "8u6708", "9u6708", "10u6708", "11u6708", "12u6708"],
# "high": [33, 27, 34, 27, 29, 27, 27, 33, 33, 34, 29, 26],
# "low": [17, 19, 11, 13, 7, 6, 6, 7, 15, 5, 13, 19]}
# -----------------------------------------------------------------------------------------------
# tolist() 可正常使用
high= nphigh.tolist()
low=nplow.tolist()
json.dumps({'month':monthstr,'high':high,'low':low})
# {"month": ["1u6708", "2u6708", "3u6708", "4u6708", "5u6708", "6u6708", "7u6708", "8u6708", "9u6708", "10u6708", "11u6708", "12u6708"],
# "high": [29, 21, 22, 22, 31, 29, 21, 20, 32, 22, 20, 23],
# "low": [17, 19, 10, 9, 17, 8, 14, 16, 18, 13, 13, 10]}

正常列表的json.dumps使用方式

代码语言:javascript复制
# 正常列表使用方法
high=[29, 33, 31, 20, 32, 32, 20, 25, 33, 20, 21, 27]
low=[8, 12, 17, 8, 6, 17, 8, 17, 14, 9, 8, 18]
json.dumps({'month':monthstr,'high':high,'low':low},ensure_ascii=False)
# {"month": ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
# "high": [29, 33, 31, 20, 32, 32, 20, 25, 33, 20, 21, 27],
# "low": [8, 12, 17, 8, 6, 17, 8, 17, 14, 9, 8, 18]}
json.dumps({'month':monthstr,'high':high,'low':low})
# {"month": ["1u6708", "2u6708", "3u6708", "4u6708", "5u6708", "6u6708", "7u6708", "8u6708", "9u6708", "10u6708", "11u6708", "12u6708"],
# "high": [29, 33, 31, 20, 32, 32, 20, 25, 33, 20, 21, 27],
# "low": [8, 12, 17, 8, 6, 17, 8, 17, 14, 9, 8, 18]}

0 人点赞