解决Python TypeError: Object of type int64 is not JSON serializable

错误场景:在使用json.dumps时,出现问题: TypeError: Object of type int64 is not JSON serializable

问题分析

  • python3中没有int64这个数据类型,所有的整型都是int
  • 报错里的int64指的是,所以很有迷惑性
  • 同样的还会出现 TypeError: Object of type float32/float64 is not JSON serializable

解决方案1

TypeError: Object of type int64 is not JSON serializable

def default_dump(obj):
    """Convert numpy classes to JSON serializable objects."""
    if isinstance(obj, (np.integer, np.floating, np.bool_)):
        return obj.item()
    elif isinstance(obj, np.ndarray):
        return obj.tolist()
    else:
        return obj
        
json.dumps(new_config,ensure_ascii=False, default=default_dump)

解决方案2

import json

class JsonEncoder(json.JSONEncoder):
    """Convert numpy classes to JSON serializable objects."""

    def default(self, obj):
        if isinstance(obj, (np.integer, np.floating, np.bool_)):
            return obj.item()
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(JsonEncoder, self).default(obj)
        
json.dumps(new_config,ensure_ascii=False, cls=JsonEncoder)

问题延伸:针对flask jsonify() 序列化错误

flask < 2.2

import datatime
from flask import Flask as _Flask
from flask.json import JSONEncoder as _JSONEncoder

class FlaskJSONEncoder(_JSONEncoder):
    """重载flask的json encoder, 确保jsonfy()能解析numpy的json"""

    def default(self, obj):
        if isinstance(obj, (np.integer, np.floating, np.bool_)):
            return obj.item()
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, (datetime.datetime, datetime.timedelta)):
            return obj.__str__()
        else:
            return super(FlaskJSONEncoder, self).default(obj)

class Flask(_Flask):
    """重载flask的jsonencoder, 确保能解析numpy的json"""
    json_encoder = FlaskJSONEncoder
    
app = Flask(__name__)

flask >= 2.2

import datatime
from flask import Flask as _Flask
from flask.json.provider import DefaultJSONProvider, _default as FlaskDefault
        
class FlaskJSONProvider(DefaultJSONProvider):
   """重载flask的json encoder, 确保jsonfy()能解析numpy的json"""
    
    @staticmethod
    def _default(obj):
        if isinstance(obj, (np.integer, np.floating, np.bool_)):
            return obj.item()
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, (datetime.datetime, datetime.timedelta)):
            return obj.__str__()
        else:
            return FlaskDefault(obj)
	
	default = _default


class Flask(_Flask):
    """重载flask的json_provider_class, 确保能解析numpy的json"""
    json_provider_class = FlaskJSONProvider
    
app = Flask(__name__)

你可能感兴趣的:(Python,数据结构,算法,python)