Mehdi Rostami Mehdi Rostami - 1 month ago 5
JSON Question

making json array in django

# view code:
response_data = []

for p in product:
response_record = {}
response_record['pname'] = p.name
response_data.append(response_record) ...
# make json type array end
return HttpResponse(json.dumps(response_data, default=date_handler,
sort_keys=True), "application/json")



For example, i want to get values like response.product.pname in ajax response:


# expected json output:

{
["product": {"pname": 'a', "pid": '2'}]

}

Answer

I finaly found choice

view:

def search(request):

    if request.method == 'POST' and request.is_ajax():
        value = request.POST.get('value')
        products = product.objects.filter(p_name__icontains=u'%s' % value)#Convert to unicode



        #make json type array begin
        response_data = []
        final_response = {}

        for p in product:
            response_record = {}
            response_record['pname'] = p.name
            response_record['pid'] = p.id
            response_data.append(response_record)

        final_response["product"] = response_data
        #make json type array end
        return HttpResponse(json.dumps(final_response, default=date_handler, sort_keys=True), "application/json")

    else:
        return HttpResponse("Bad Request Detected!! :(")

JS:

$.ajax({
        type: 'POST',
        url: '/Search/',
        data:{value:val},
        dataType: "json",
        success:function(response)
        {             

                     $.each(response.product, function (i, val)
                    {
                    alert(val.pname+" "+val.pid);

                    }
                         );


        }
Comments