0

I'm looking to iterate through a JSON object in javascript. Right now it is loading each "item" into a single cell instead of putting 1 item per column across a row. For example, I want to get:

Period         Name          Amount
1/1/2014    Accounting       $500.00

What I'm getting is:

       Period                             Name                Amount
1/1/2014, Accounting, $500       1/1/2014, Finance, $750    ...,...,...

The view producing the JSON object is:

def BudgetJson(request):
    from django.http import JsonResponse
    resultset = models.Expense.objects.filter(category_id=1)
    d = {'data' : [[[model.expensePeriod, model.expenseName, 
           model.expenseAmount] for model in resultset]]}
    return JsonResponse(d)

I'm using the datatables library to render the table, and using AJAX to receive the JSON object (via a URL):

<script type="text/javascript" class="init">

    $(document).ready(function() {
        $('#expenses').DataTable( {
            "ajax": '{% url "property:budget:budget_json" %}'
        });
    });
</script>

I understand that my view is outputting a single key/item, which is why I'm getting that result - what I want to know is, is it better to let the JavaScript loop through the JSON object, and is that possible using the datatables UI library? Or should I change the structure of the JSON object that the view is outputting?

1
  • What version of Datatables are you using? I ask because there was a complete overhaul of the API in 1.10. Commented Apr 30, 2015 at 3:09

1 Answer 1

2

You can do this way,
producing JSON Object:

def BudgetJson(request):
    from django.http import JsonResponse
    out_list = []
    resultset = models.Expense.objects.filter(category_id=1)
    for model in resultset:
        temp_dict = {'expense_period': model.expensePeriod, 'expense_name':model.expenseName, 'expense_amount':model.expenseAmount }
        out_list.append(temp_dict)
    data = {'data' : out_list }
    return HttpResponse(json.dumps(data), content_type='application/json')

and inside your <script> tag the datatable will as

$('#expenses').DataTable( {
                    "ajax" : "your-url",
                    "columns" : [
                    {"data" : "expense_period"},
                    {"data" : "expense_name"},
                    {"data" : "expense_amount"},
                    ]
                });

This will work. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.