2012-09-30 56 views
35

现在我目前只是做这个:如何正确输出JSON与应用程序引擎Python webapp2?

self.response.headers['Content-Type'] = 'application/json' 
self.response.out.write('{"success": "some var", "payload": "some var"}')

有没有更好的办法使用一些图书馆办呢?

+0

http://stackoverflow.com/questions/1171584/how-can-i-parse-json-in-google-app-engine –

回答

57

是的,你应该使用在Python 2.7版支持json library

import json 

self.response.headers['Content-Type'] = 'application/json' 
obj = { 
    'success': 'some var', 
    'payload': 'some var', 
} 
self.response.out.write(json.dumps(obj)) 
+2

Doh!我一直在使用'self.response.headers ['Content-Type:'] ='application/json',并拉我的头发。无意中在那里添加了一个冒号。 – Jonny

12

蟒本身有json module,这将确保您的JSON格式正确,手写JSON是更容易得到错误。

import json 
self.response.headers['Content-Type'] = 'application/json' 
json.dump({"success":somevar,"payload":someothervar},self.response.out) 
+1

我可能是错的,但我怀疑这实际上是这样工作的。为什么你会将'self.response.out'作为参数传递给'dump'函数? – aschmid00

+12

它的确如此。 self.response.out是一个流,dump()将流作为其第二个参数。 (也许你对dump()和dumps()之间的区别感到困惑?) –

31

webapp2有json模块方便的包装:如果可用它将使用simplejson,或用Python> = 2.6(如果可用),并作为最后的资源在App的django.utils.simplejson模块json模块发动机。

http://webapp2.readthedocs.io/en/latest/api/webapp2_extras/json.html

from webapp2_extras import json 

self.response.content_type = 'application/json' 
obj = { 
    'success': 'some var', 
    'payload': 'some var', 
    } 
self.response.write(json.encode(obj)) 
0
import json 
import webapp2 

def jsonify(**kwargs): 
    response = webapp2.Response(content_type="application/json") 
    json.dump(kwargs, response.out) 
    return response 

要返回一个JSON响应每到一个地方......

return jsonify(arg1='val1', arg2='val2') 

return jsonify({ 'arg1': 'val1', 'arg2': 'val2' }) 
3

我通常使用这样的:

class JsonEncoder(json.JSONEncoder): 
    def default(self, obj): 
     if isinstance(obj, datetime): 
      return obj.isoformat() 
     elif isinstance(obj, ndb.Key): 
      return obj.urlsafe() 

     return json.JSONEncoder.default(self, obj) 

class BaseRequestHandler(webapp2.RequestHandler): 
    def json_response(self, data, status=200): 
     self.response.headers['Content-Type'] = 'application/json' 
     self.response.status_int = status 
     self.response.write(json.dumps(data, cls=JsonEncoder)) 

class APIHandler(BaseRequestHandler): 
    def get_product(self): 
     product = Product.get(id=1) 
     if product: 
      jpro = product.to_dict() 
      self.json_response(jpro) 
     else: 
      self.json_response({'msg': 'product not found'}, status=404) 
相关问题