Home > Software engineering >  Respond an array of json objects in Django view
Respond an array of json objects in Django view

Time:10-25

I have this table or model:

longitude latitude session
12 34 1
99 42 2
99 42 1
99 42 3
99 42 1
99 42 2

I need to make a query to get all data by session. So I get all the data from the table and apply 'distinct' to get the sessions:

sessions= GPSData.objects.values('session_new_id').distinct()

I get:

<QuerySet [{'session': 1}, {'session': 2}, 'session': 3}]>

Now, for each session I need to get longitude an latitude. Afterwards I need to send an HttpResponse with the data in a JSON. So I'm trying in my view:

def get_all_gps(request):
    data=[]   
    for session in sessions:
        y=GPSData.objects.filter(session=session['session'])
        y = serializers.serialize("json", y)
        data.append(y)
        return HttpResponse(data, content_type='application/json')

I get an error in the template because I am passing an array not a json object:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 190986 of the JSON data

In general what I need is to respond with an array of JSON objects. Something like this:

[[{json from session 1}],[{json from session 2}],[{json from session 3}]]

Can this be done?

CodePudding user response:

I've followed the link @Mike Jones has commented and was able to do it using JsonResponse.

from django.http import JsonResponse
from .models import GPSData

def get_all_gps(request):
    data = []   
    for gps_data in GPSData.objects.all().order_by("session").values():
        try:
            session_list = next(l for l in data if l[0]["session"] == gps_data["session"])
        except StopIteration:
            session_list = []
            data.append(session_list)
        session_list.append(gps_data)
    return JsonResponse(data, safe=False)
  • Related