Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing json formatted requests in appengine

Been working on an appengine app lately. I would like to parse json data contained in requests to the app. How do I use the request object of the requesthandler class to achieve this?

Below is a snippet of the code to show what I want to achieve:

import cgi
import webapp2
import datamethods

from google.appengine.ext.webapp.util import run_wsgi_app

class adduser(webapp2.RequestHandler):
    def get(self):
        # Get the phone number from json data in request.
        userphone = self.request.get("phone")
        # Get the name from json data in request.
        name = self.request.get("name")


app = webapp2.WSGIApplication([
  ('/adduser', adduser),
  ('/sign', updatestatus),
  ('/login',login)
], debug=True)


def main():
    run_wsgi_app(app)

if __name__ == "__main__":
    main() 
like image 351
koladotnet Avatar asked Aug 23 '12 11:08

koladotnet


2 Answers

You have to parse the incoming json string in an object. After this you can access the attributes.

import json   # Now you can import json instead of simplejson
....
jsonstring = self.request.body
jsonobject = json.loads(jsonstring)
like image 153
voscausa Avatar answered Sep 30 '22 00:09

voscausa


import cgi
import webapp2
import datamethods

from google.appengine.ext.webapp.util import run_wsgi_app

class adduser(webapp2.RequestHandler):
    def get(self):
        items = [] 
        response = { }

        userphone = self.request.get("phone") 
        name = self.request.get("name")

        items.append({'userphone': userphone , 'name':name})
        response['userInformation'] = items
        return response #return json data


app = webapp2.WSGIApplication([
  ('/adduser', adduser),
  ('/sign', updatestatus),
  ('/login',login)
], debug=True)


def main():
    run_wsgi_app(app)

if __name__ == "__main__":
    main()
like image 26
okan kilic Avatar answered Sep 30 '22 00:09

okan kilic