user8573812
user8573812

Reputation:

Unable to convert dictionary object to JSON object

I want to convert my dictionary object as a JSON as i need to send it in ReactJS file. My code is below:

def get(self, request, pk, format = None):
    queryset = SocialAccount.objects.filter(provider='twitter').get(id=pk)
    user_id= queryset.uid
    name = queryset.extra_data['name']
    username = queryset.extra_data['screen_name']
    data = {'user_id':user_id,'name':name,'username':username}
    data = json.dumps(data)
    print(type(json.loads(data)))
    return Response(json.loads(data))

In this view, I got " class 'dict' " in "print(type(json.loads(data)))" line instead of JSON object. If i am going wrong, please guide me. What i need to do? Thanks.

Upvotes: 0

Views: 1647

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121416

You successfully produced JSON. What you did wrong is that you then decoded the JSON again, back to a Python object, and you only tested the result of that decoding. And that is rightly a new dictionary object; the JSON you produced and stored in data is valid JSON and you have proved it could be decoded again, successfully.

In other words, don't decode again. You already have JSON, just return that:

data = {'user_id':user_id,'name':name,'username':username}
data = json.dumps(data)
return Response(data)

You can simplify this with returning a JsonResponse object instead:

# at the top
from django.http import JsonResponse

# in your view
data = {'user_id':user_id,'name':name,'username':username}
return JsonResponse(data)

This also takes care of setting the right content type for you.

Upvotes: 4

ettanany
ettanany

Reputation: 19806

You can use JsonResponse instead of Response:

def get(self, request, pk, format=None):
    # ...
    data = {'user_id': user_id,'name': name,'username': username}
    return JsonResponse(data)

Your issue is that you converted your data back to Python object by using json.loads(data). Instead you just need to return Response(data) but you should prefer JsonResponse.

Upvotes: 3

Related Questions