【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,
    }

你可能感兴趣的:(编程语言,python,json)