1

I've built a Django view for the sake of returning a pure JSON object:

from django.core import serializers
import json
def testjson(request):
    all_objects = list(Message.objects.all())

    to_json = serializers.serialize('json', all_objects)

    return HttpResponse(json.dumps(to_json), mimetype='application/json')

to_json above only ends up looking something like this:

\"employees\": [
{ \"firstName\":\"John\" , \"lastName\":\"Doe\" }, 
{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" }, 
{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }
]

This is completely useless with the \ and I can't figure out how to get rid of them. I've tried this but the \ triggers an escape character:

to_json = to_json.replace('\', '')

How do I change the JSON object to replace the \" with just "?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
user1504605
  • 579
  • 5
  • 19
  • Are you evaluating this in the interactive Python shell? If so, this could be an artifact of that, since the shell automatically escapes the hyphens. – ThePhysicist Apr 14 '14 at 03:52

1 Answers1

3

You don't need to call json.dumps(), serialize() would make a json string for your response:

from django.core import serializers

def testjson(request):
    data = serializers.serialize('json', Message.objects.all())
    return HttpResponse(data, mimetype='application/json')

Also see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195