1. 程式人生 > >json自定制

json自定制

bsp tom status sta ins elif obj json.js .data

import json
from datetime import date
from datetime import datetime


class JsonCustomEncoder(json.JSONEncoder):
    def default(self, field):
        if isinstance(field, datetime):
            return field.strftime(%Y-%m-%d %H)
        elif isinstance(field, date):
            return field.strftime(
%Y-%m-%d) elif isinstance(field, Response): return field.__dict__ else: return json.JSONEncoder.default(self, field) class Response(object): def __init__(self): self.status =True self.data = "asdf" data = { k1: 123, k2: datetime.now(),
k3: Response() } ds = json.dumps(data, cls=JsonCustomEncoder) print(ds)

json自定制