简体   繁体   中英

Looping through a nested JSON object in datatables

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?

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. :)

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