I am sending json data to api but getting unicode

2019-09-11 02:23发布

问题:

My data -:

{"op":"merge","merge_bcards_ids":{"data":[216,217]},"target_bacard_id":226}

In view file I am getting json list data request.data["merge_bcards_ids"] :-

[258, 259] <type 'list'> which is showing correct.

But when this api call from external device then :-

[257,258] <type 'unicode'>

So I want list instead of unicode. Please help me out.

My view is :-

class BusinessViewSet(viewsets.ModelViewSet):
   queryset = BusinessCard.objects.all()
   serializer_class = BusinessCardSerializer

   def create(self, request):
       try:
          op = request.data["op"]
       except:             
          op = None

       if op == 'merge':
              try:
                 merge_bcards_ids = request.data["merge_bcards_ids"]
                 target_bacard_id = request.data["target_bacard_id"]
              except:
                 merge_bcards_ids = None
                 target_bacard_id = None
              print merge_bcards_ids   
              print merge_bcards_ids.__class__

回答1:

request params are strings.

You may dump you dictionary (json.dumps) and sent it as a request param. On other side you must to use json.loads to convert you data back to dict.

Also you can dump only array "data":json.dumps([216,217]) and then load it as array: json.loads(request.data["merge_bcards_ids"]).

It may cause some encoding/decoding errors (it depends on version of python you are using)



回答2:

I don't know why the data is coming as unicode, I also passed through this same situation once and i solved by converting from unicode data to normal; This code may help you to do that;

if isinstance(request.data['merge_bcards_ids'], unicode):
    merge_bcards_ids = list(unicodedata.normalize('NFKD', request.data['merge_bcards_ids']).encode('ascii','ignore'))
else:
    merge_bcards_ids = request.data['merge_bcards_ids']

OR

merge_bcards_ids = [unicodedata.normalize('NFKD', ids).encode('ascii','ignore') for ids in list(unicodedata.normalize('NFKD', request.data['merge_bcards_ids']).encode('ascii','ignore'))).encode('ascii','ignore')]


回答3:

Make sure you are using the "application/json" content type when submitting your request.