Skip to content

Instantly share code, notes, and snippets.

@Thesharing
Last active November 15, 2017 13:40
Show Gist options
  • Save Thesharing/f00ce244964d8a4b2ea245e3bec109ce to your computer and use it in GitHub Desktop.
Save Thesharing/f00ce244964d8a4b2ea245e3bec109ce to your computer and use it in GitHub Desktop.
Python中Json库的使用

json库如何解析Decimal

在解析含有Decimal的元素时,json会报错:

TypeError: Decimal is not JSON serializable

参考一下19.2. json — JSON encoder and decoder中对dump参数的描述:

If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.

因此通过声明default函数可以解决Decimal无法Json Serialize的问题,代码如下:

import json
from decimal import Decimal

def decimal_default(obj):
    if isinstance(obj, Decimal):
        return float(obj)
    raise TypeError

d = {"Num": Decimal(5,5)}
print(json.dumps(d, default=decimal_default))

json库生成的str中中文为Unicode码

设置ensure_ascii = False

即:

import json

d = {"Text": "你好"}
print(json.dumps(d, ensure_ascii = False))

完整用法

import json
from decimal import Decimal
from datetime import date
from datetime import datetime

def json_default(obj):
    if isinstance(obj, Decimal):
        return float(obj)
    elif isinstance(obj, date):
        return obj.isoformat()
    elif isinstance(obj, datetime):
        return obj.strftime("%Y-%m-%d %H:%M:%S")
    raise TypeError

json.dumps(d, default=json_default, ensure_ascii = False)

参考

Python to JSON Serialization fails on Decimal - StackOverflow

python 打印json格式的数据中文显示问题 - CSDN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment