Reputation: 357
I'm passing an object of data from a Python/Django App to the front end using AJAX in JSON form. Everything is working correctly, except that I cannot parse the JSON object once in Javascript. I keep getting undefined. I've tried every approach I could think of and I am super stuck so I wanted to see if someone might be able to point out what I hope is a super simple oversight!
Snippet of Python/Django:
data = serializers.serialize('json', products)
response = {'product_data': data,
'product_count': product_count}
return HttpResponse(json.dumps(response), content_type='application/json')
Snippet of AJAX Callback:
.done(function(data){
console.log(data.product_count)
console.log(data.product_data)
console.log(data.product_data["model"])
console.log(data.product_data[0])
console.log(data.product_data[0]["model"])
})
Console Logs Response Snippet:
>1
>[{"model": "seller.product", "pk": 11048, "fields": {"seller": 132, "width": 211, "height": 3, "length": 350, "weight": 18600, "price": 11077, "color_id": null, "po_number": null, "po_sub_number": null, "custom_order_id": null, "active_at": "2019-08-02T01:27:23.410Z", "deactive_at": null, "in_holding": false, "approved_at": "2019-08-04T15:34:08.318Z", "sold_at": "2020-02-07T20:07:54.675Z", "slug": "colored-beni-ourain-rug", "created_at": "2019-08-02T01:23:51.650Z", "updated_at": "2020-02-07T20:07:54.675Z", "assets": [3567, 3581, 3585, 3572, 3573, 3574, 3577, 3582, 3583, 3584, 3586, 3587, 3589, 3594, 3596], "colors": [1, 2, 3, 4, 12], "shipping_options": [1]}}]
> undefined
> [
> undefined
The first console log of 1 is correct and in the second line the data I want is all there. But any time I try and get info out of it I just get undefined or a ] and I cannot figure it out. Can anyone help? Thank you!
Upvotes: 1
Views: 689
Reputation: 688
Use JSONResponse instead of HttpResponse. That way you don't need to handle anything in between.
return JSONResponse(products)
:)
"json.dumps" would've been sufficient tho, no need for another call to the serializer.
Upvotes: 1
Reputation: 97672
You're serializing you data multiple times, just put products
into response
without serializing it.
response = {'product_data': products,
'product_count': product_count}
return HttpResponse(json.dumps(response), content_type='application/json')
Upvotes: 1