Rod
Rod

Reputation: 81

Serialization is returning each character as object

I have a simple view, in which I need to return JSON data but when using django serialize and JsonResponse it returns each character as an object. Here is the snippet:

def query(request):
    data = serializers.serialize('json', Post.objects.all())
    response = JsonResponse(data, safe=False)
    return response

The problem is that if I want to print response.content[0] it returns some random number as it's the first character of the response.

Is there any way I can make the response to be accessed like a simple dictionary (JSON)?

Upvotes: 0

Views: 125

Answers (1)

masnun
masnun

Reputation: 11906

Once you have a JSON, it's basically a string - so you can not access it like a dictionary/list or any Python type.

If you need to access it like a dictionary or a list, you should operate on the non serialized data:

def query(request):
    posts = Post.objects.all()

    print(posts[0]) # You can now use it as a list of objects

    data = serializers.serialize('json', posts)
    response = JsonResponse(data, safe=False)
    return response

Upvotes: 1

Related Questions