koladotnet
koladotnet

Reputation: 71

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() 

Upvotes: 7

Views: 6640

Answers (2)

voscausa
voscausa

Reputation: 11706

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)

Upvotes: 18

okan kilic
okan kilic

Reputation: 27

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()

Upvotes: 1

Related Questions