【Python】json坑(持续更新)

python内置的json

json.dumps()         #将Python中的对象转换为JSON中的字符串对象
json.loads()         #将JSON中的字符串对象转换为Python中的对象

这个问题是由于json.dumps()函数引起的。dumps是将dict数据转化为str数据,但是dict数据中包含byte、int、float、datetime等等的时候,数据所以会报错。

可能会遇到TypeError: Object of type xxx is not JSON serializable错误,也就是无法序列化某些对象格式。

注意:json默认支持的类型只有下面几种,其他的类型,比如自定义的类或者date类型,都需要自定义jsonEncoder。

    Supports the following objects and types by default:

    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

TypeError: Object of type ValueError is not JSON serializable

json.dumps()

numpy array 不能用json包起来当做出参。

numpy array 不能用json包起来。
TypeError: Object of type 'ndarray' is not JSON serializable

图片img(RGB)也不能用json包起来

from PIL import Image
图片img(RGB)也不能用json包起来。
TypeError: Object of type 'Image' is not JSON serializable

python使用raise ValueError('修改信息失败')抛出异常,使用如下捕获异常:

except ValueError as e:
    traceback.print_exc()
    return {
        'msg': e,                #错误写法
        'code': 400,
    }
except ValueError as e:
    traceback.print_exc()
    return {
        'msg': str(e),          #正确写法
        'code': 400,
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值