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

本文介绍了如何使用Python的json模块和自定义encoder将numpy数组转换为可序列化的JSON格式,包括解决TypeError: Object of type 'ndarray' is not JSON serializable问题的方法,以及tolist()与list()的区别。
摘要由CSDN通过智能技术生成

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

ece07b1f2798d583bf2200bd1ae13737.png

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

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

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构造随机数

# 初始化数据
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错误以及解决办法

# ---------------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": ["1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708"],
# "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类型。

# ---------------------------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": ["1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708"],
# "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": ["1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708"],
# "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使用方式

# 正常列表使用方法
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": ["1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708", "9\u6708", "10\u6708", "11\u6708", "12\u6708"],
# "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]}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

python与大数据分析

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值