Search code examples
pythonjsongoogle-app-enginewebapp2webob

Google App Engine: Python: WebOb: How to get POST data in JSON format?


I am building a web app on the Google App Engine platform, which uses webapp2, which uses WebOb. I would like to POST some data in JSON format, including nested arrays and dictionaries. E.g.:

$.post('/addvendor', {'vendor': {'name': 'test', 'description': 'a good company', 'tags':['foo', 'bar']}}, function(data){console.log(data)}, 'application/json')

However, on the server side, the data comes in as a flat "MultiDict" object, not anything like the original nested JSON object that I POSTed. E.g.:

>>> print self.request.params.items()
[(u'vendor[name]', u'test'), (u'vendor[description]', u'a good company'), (u'vendor[tags][]', u'foo'), (u'vendor[tags][]', u'bar')]

This object is very difficult to parse. In my server code, is there a way to get the same data in standard JSON format, or at least a Python equivalent using nested dictionaries and arrays, on the server so that I can manipulate and examine the data easily?


Solution

  • (updated with jayhendren's help) You should use $.ajax and manually set contentType='application/json; charset=utf-8' instead because $.post uses default "application/x-www-form-urlencoded;" content type. Also you need to manually encode data to JSON-string with JSON.stringify:

    $.ajax({url:'/addvendor', 
            type: 'post', 
            data:JSON.stringify({'vendor': {'name': 'test', 'description': 'a good company', 'tags':['foo', 'bar']}}), 
            contentType:'application/json; charset=utf-8',
            dataType: "json",
            success:function(data){console.log(data)}})
    
    ...
    
    print json.loads(self.request.body)