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.
-
1Possible duplicate of Convert Python dictionary to JSON arrayuser8688484– user86884842017年11月01日 09:57:56 +00:00Commented Nov 1, 2017 at 9:57
-
@pm95: that hardly covers the mistake made here, that the OP then decoded again.Martijn Pieters– Martijn Pieters2017年11月01日 10:03:04 +00:00Commented Nov 1, 2017 at 10:03
-
because you dumped and loaded it back to dictbe_good_do_good– be_good_do_good2017年11月01日 10:10:48 +00:00Commented Nov 1, 2017 at 10:10
2 Answers 2
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.
4 Comments
str object. That's correct. Try printing the value itself.json.dumps() function does what it says on the tin, it doesn't add extra characters that were not already there in the input data structure or are needed to make the document valid JSON. Look at what the view returns in a browser, for example, or use an online JSON validator to see that the value really is a valid JSON document.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.