如何使用app engine Python webapp2正确输出JSON?

38

目前我只是这样做:

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

是否有使用某个库更好的方法来完成这个任务?


https://dev59.com/bnM_5IYBdhLWcg3w6HzT - Markus von Broady
5个回答

60

是的,您应该使用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))

2
糟糕!我一直在使用self.response.headers['Content-Type:'] = 'application/json',结果卡了好久。不小心多加了一个冒号。 - Jonny

31

webapp2对于json模块有一个方便的封装:如果可用,它将使用simplejson,否则将使用Python>= 2.6中的json模块,并且在App Engine上作为最后的资源使用django.utils.simplejson模块。

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

13

Python自带JSON模块,使用它可以确保你的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()之间的区别而感到困惑?) - Guido van Rossum

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)

1
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' })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接