简体   繁体   中英

Django: custom object json serialization

I want to serialize a custom object in json format, where entryData is a list of my domain object. Something like this:

{
    "total":2,
    "current":1,
    "entryData":[
        {
            "id":1,
            "version":0,
            "name":"Default Station"
        },
        {
            "id":2,
            "version":3,
            "name":"Default Station 1"
        }
    ]
}

Here what I have done to get json output in one of my attempt:

def ground_station_listgrid(request):
    entryData = serializers.serialize("json", GroundStation.objects.all())
    response_data = {}
    response_data['totalPages'] = 2
    response_data['currentPage'] = 1
    response_data['entryData'] = entryData

    return HttpResponse(json.dumps(response_data),mimetype='application/json')

but the result is entryData evaluated as a string, with quotes escaped:

{
"totalPages": 1, 
"currentPage": 1, 
"entryData": "[{\"pk\": 1, \"model\": \"satview.groundstation\", ....

I have also tryed to do something like this:

def ground_station_listgrid(request):

    response_data = {}
    response_data['totalPages'] = 1
    response_data['currentPage'] = 1
    response_data['entryData'] = GroundStation.objects.all()

    return HttpResponse(json.dumps(response_data),mimetype='application/json')

But I get this exception: [<GroundStation: nome>, <GroundStation: nome>, <GroundStation: nome>] is not JSON serializable

Can someone please poin me in right direction?

Thanks in advance Marco

You can use model_to_dict() :

def ground_station_listgrid(request):
    data = [model_to_dict(instance) for instance in GroundStation.objects.all()]
    response_data = {}
    response_data['totalPages'] = 1
    response_data['currentPage'] = 1
    response_data['entryData'] = data

    return HttpResponse(json.dumps(response_data),mimetype='application/json')

Though I prefer to use included in django batteries: django.core.serializers , but, since you have a custom json response, model_to_dict() appears to be the way to go.

There are other options here (like use of values_list() ):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM