如何使用应用引擎 Python webapp2 正确输出 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12664696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly output JSON with app engine Python webapp2?
提问by Ryan
Right now I am currently just doing this:
现在我目前只是这样做:
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write('{"success": "some var", "payload": "some var"}')
Is there a better way to do it using some library?
有没有更好的方法来使用某个库来做到这一点?
回答by Lipis
Yes, you should use the jsonlibrarythat is supported in Python 2.7:
是的,您应该使用Python 2.7 支持的json库:
import json
self.response.headers['Content-Type'] = 'application/json'
obj = {
'success': 'some var',
'payload': 'some var',
}
self.response.out.write(json.dumps(obj))
回答by Xuan
webapp2has a handy wrapper for the json module: it will use simplejson if available, or the json module from Python >= 2.6 if available, and as a last resource the django.utils.simplejson module on App Engine.
webapp2有一个方便的 json 模块包装器:它将使用 simplejson(如果可用)或 Python >= 2.6 中的 json 模块(如果可用),以及 App Engine 上的 django.utils.simplejson 模块作为最后一个资源。
http://webapp2.readthedocs.io/en/latest/api/webapp2_extras/json.html
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))
回答by bigblind
python itself has a json module, which will make sure that your JSON is properly formatted, handwritten JSON is more prone to get errors.
python 本身有一个json 模块,它将确保您的 JSON 格式正确,手写 JSON 更容易出错。
import json
self.response.headers['Content-Type'] = 'application/json'
json.dump({"success":somevar,"payload":someothervar},self.response.out)
回答by nguyên
I usually using like this:
我通常这样使用:
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)
回答by Travis Vitek
import json
import webapp2
def jsonify(**kwargs):
response = webapp2.Response(content_type="application/json")
json.dump(kwargs, response.out)
return response
Every place you want to return a json response...
你想返回一个json响应的每个地方......
return jsonify(arg1='val1', arg2='val2')
or
或者
return jsonify({ 'arg1': 'val1', 'arg2': 'val2' })

