2012-08-23 13 views
6

Ultimamente ho lavorato a un'app di appengine. Vorrei analizzare i dati JSON contenuti nelle richieste per l'app. Come posso utilizzare l'oggetto richiesta della classe requesthandler per raggiungere questo obiettivo?parsing json formatted requests in appengine

Qui di seguito è un frammento di codice per mostrare ciò che voglio raggiungere:

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

risposta

17

Bisogna analizzare la stringa JSON in entrata in un oggetto. Dopo questo è possibile accedere agli attributi.

import json # Now you can import json instead of simplejson 
.... 
jsonstring = self.request.body 
jsonobject = json.loads(jsonstring) 
+0

brilliant..thanks .... ho usato la libreria JSON insito in questo modo:

 import json class message(webapp.RequestHandler): def post(self): self.response.headers['Content-Type'] = "text/plain" # self.response.out.write(self.request.body) data = json.loads(self.request.body) self.response.out.write(data['sux']) 
e che risolve ... – koladotnet

+1

non si ha realmente bisogno ancora semplice JSON, perché non solo jSON? –

+0

dall'SDK di Python versione 1.9.55. puoi usare ujson. UltraJSON è un codificatore e decodificatore JSON ultrarapido scritto in puro C – voscausa

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