结构体 字典 json 序列化 差异 json序列化器 浮点数序列化
实践:
1、
import "encoding/json" func mapVstruct2jsonMarshal() { t := struct { A string B int32 C bool }{"a", 123, true} m := map[string]interface{}{ "A": "a", "B": 123, "C": true, } b1, _ := json.Marshal(t) b2, _ := json.Marshal(m)
t := map[string]interface{}{
"app_key": app_key,
"version": version,
"timestamp": timestamp_int,
"nonce_str": nonce_str,
"sign": sign,
}
p, _ := json.Marshal(t)
https://mp.weixin.qq.com/s/dvLzS3t51Hq_fPK1FkumyQ
# -*- coding: UTF-8 -*- import decimal import json class DecimalEncoder(json.JSONEncoder): ''' json.dumps(str) --> Object of type Decimal is not JSON serializable json.dumps(str,cls=DecimalEncoder) ''' def default(self, o): if isinstance(o,decimal.Decimal): return float(o) super(DecimalEncoder,self).default(o) import json from utils.util_json import DecimalEncoder as util_DecimalEncoder burst_feature_str = json.dumps(burst_feature,cls=util_DecimalEncoder)
集合转列表
import datetime import decimal import uuid from flask.json import JSONEncoder as BaseJSONEncoder class JSONEncoder(BaseJSONEncoder): def default(self, o): app.logger.info(o) import pprint pprint.pprint(o) if isinstance(o, datetime.datetime): # 格式化时间 return o.strftime("%Y-%m-%d %H:%M:%S") if o is not None else None if isinstance(o, datetime.date): # 格式化日期 return o.strftime('%Y-%m-%d') if o is not None else None if isinstance(o, decimal.Decimal): # 格式化高精度数字 return str(o) if isinstance(o, uuid.UUID): # 格式化uuid return str(o) if isinstance(o, bytes): # 格式化字节数据 return o.decode("utf-8") if isinstance(o,set): return list(o) return super(JSONEncoder, self).default(o)