aldesabido aldesabido - 1 year ago 121
AngularJS Question

Django unicode objects from Angular request

When I call a post request from angular and pass a data then receive in django views, the data becomes an object with unicode keys and values.


//from angular
$"url_here",{"name" : "alde","grade" : 94})

data_from_angular = json.loads(request.body.decode("utf-8"))
>>>> {u'name' : u'alde', u'grade' : u'84'} // this is the problem
>>>> {'name' : 'alde', 'grade' : 84} // I want this result so that I can have the 'grade' as number not unicode.

I hope that you can help me with this. Thanks!


The problem is in my JSON data. the number 84 was denoted as string. Thanks to @Sudlip for pointing my problem.

Answer Source

The u-prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data.

If you really wish to convert it to normal string you can convert both key and value using dictionary comprehension and str keyword.:

data_from_angular = dict((str(k), str(v)) for k, v in data_from_angular.items())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download