Ahmad Javed
Ahmad Javed

Reputation: 612

How to correct the format given by JsonResponse

I am printing the output from my views function in Django using JsonResponse and want to correct the output and only include certain fields.How should I proceed?

The function is :

    influencers = Influencer.objects.all()

    influencer_data = serializers.serialize("json",influencers)    
    context = {
        'influencer_data':influencer_data,
    }

    return JsonResponse(context)

The output/returned value is:

{"influencer_data": "[{\"model\": \"influencer_listings.influencer\", \"pk\": 7250, \"fields\": {\"full_name\": \"Be Yourself\", \"username\": \"tapasya_agnihotri\", \"photo\": \"\", \"email_id\": \"\", \"external_url\": \"\", \"location_city\": \"Kolkata\" The output is like the one given above.However I want the output to be without the slashes.Also why is JsonResponse printing the slashes.

Upvotes: 1

Views: 62

Answers (2)

JPG
JPG

Reputation: 88459

As I've already mentioned here, How do you serialize a model instance in Django?, Use python serializer instead of json

influencers = Influencer.objects.all()

influencer_data = serializers.serialize("python",influencers)    
context = {
    'influencer_data':influencer_data,
}

return JsonResponse(context)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

You're serialising twice. If you use the built in serializers, you should just use HttpResponse and return the data directly:

influencer_data = serializers.serialize("json",influencers)    

return HttpResponse(influencer_data, content_type="application/json")

Upvotes: 1

Related Questions