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

时间:2022-03-15 19:16:39

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?

有更好的方法用图书馆来做吗?

5 个解决方案

#1


57  

Yes, you should use the json library that 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))

#2


31  

webapp2 has 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模块;应用程序引擎上的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))

#3


12  

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)

#4


3  

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)

#5


0  

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

#1


57  

Yes, you should use the json library that 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))

#2


31  

webapp2 has 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模块;应用程序引擎上的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))

#3


12  

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)

#4


3  

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)

#5


0  

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