【Python - Json】dict/json序列表dumps

from faker import Faker
import random
import decimal
import json
import datetime
from datetime import date

f = Faker(locale='zh_CN')
res = dict(f.profile())


class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        elif isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime("%Y-%m-%d")
        super(DecimalEncoder, self).default(obj)


# 引用
j = json.dumps(res, cls=DecimalEncoder, indent=4,ensure_ascii=False)
print(j)

 

posted @ 2022-05-19 15:11  情调丶  阅读(47)  评论(0编辑  收藏  举报