When I post data to the server as JSON via AJAX, values from form elements come is as strings (unicode). Here’s a simple example:
<select id="test">
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
</select>
Sending data to the server like this:
$('test').change(function(){
var id = $(this).val();
$.ajax(
{
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: someUrl,
data: JSON.stringify(id:id),
dataType: 'json',
success: doSomething
});
Then on the server (Pyramid 1.3.3):
log.debug(type(request.json_body['id'])) gives <type 'unicode'>
This makes code like if request.json_body['id'] == 2 False since the value is actually u’2′.
I’ve been doing id = int(request.json_body['id']) for all the params that should be ints, but is there a better way? I feel like I’m missing something obvious.
No, this is correct. Form element values in a web page are always strings, regardless of what you expect the end-users to enter.
You can use collander to automate the conversion on the server side though. You specify a schema, pass in the decoded JSON data structure and get a nice Python structure back, fully validated.
The simplest possible example for deserializing integers:
but colander can handle mappings, sequences, booleans, datetime objects, and much more besides.