Skip to content

Getting data from JSON to JS

In the django function, I send data to JS via JSON

 startdate = datetime.strptime(request.POST['startdate'], '%d.%m.%Y')
 enddate = datetime.strptime(request.POST['enddate'], '%d.%m.%Y')
 paymentparking = paidparking.objects.filter(expirationdate__range = (startdate, enddate)).values('expirationdate',
 return JsonResponse(dict(paymentparking))

How do I get price and expirationdate separately in JS?

    type: "POST",
    url: "statistics",
    data: {
      'startdate': finalDateStrStart,'enddate': finalDateStrEnd,
    dataType: "json",
    cache: false,
    success:function (data) {

This is what I get in the django function before sending the JSON:

<QuerySet [{'expirationdate':, 4, 30), 'price': 300.0}, {'expirationdate':, 5, 5), 'price': 750.0}]> 

If success:

function (data) {

As a result, I get:

enter image description here

I need to get the price and expirationdate separately. How can this be done?



How do I get price and expirationdate separately in JS?

In your success function, you can access the properties of the first item as data[0].expirationdate and data[0].price for example. Since you are filtering paidparking instances, you should expect more than one.

The problem is that you are not correctly creating the JSON response. Converting a QuerySet to a dict won’t do what you want. Instead, just serialize the QuerySet directly:

return JsonResponse(paymentparking, safe=False)

I set safe=False here in order to serialize the QuerySet as a JSON array.

Alternatively, you can serialize the QuerySet as a value inside a dictionary:

return JsonResponse({'result': list(paymentparking))

Then you can get the array of results through data.result in your success function. Do whatever you want with that array from there, such as data.result[0].expirationdate to get the expiration date for the first item.

For more information on JsonResponse, read the docs.