Sequence function in view

method one

from django.core import serializers # Import module
res = serializers.serialize('json', hosts_list)
return HttpResponse(res)

Second way

res = hosts_list.values('hostname', 'ip')
import json
res = json.dumps (list (res)) # Note plus function list
return HttpResponse(res)

However, this method can not be serialized, such as time data

Three ways

Custom Serialization

from datetime import datetime
from datetime import date
import json


# Create your tests here.


class CustomEncoder (json.JSONEncoder): # rewrite custom serialization method
    def default(self, field):
        if isinstance(field, datetime):
            return field.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(field, date):
            return field.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder(self, field)


d = {
    'K1': 'v1'
    'K2': 'v2',
    'datetime': datetime.now(),
}
res = json.dumps (d, cls = CustomEncoder) # the overridden serialization method to pass parameters cls
print(res)

Guess you like

Origin www.cnblogs.com/Treelight/p/12194717.html