38

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?

Ryan
  • 5,883
  • 13
  • 56
  • 93

5 Answers5

60

Yes, you should use the json library that is supported in Python 2.7:

import json

self.response.headers['Content-Type'] = 'application/json'   
obj = {
  'success': 'some var', 
  'payload': 'some var',
} 
self.response.out.write(json.dumps(obj))
Lipis
  • 21,388
  • 20
  • 94
  • 121
  • 2
    Doh! I was using `self.response.headers['Content-Type:'] = 'application/json'` all the time and pulled my strin.. hairs. Accidentally added a colon there. – Jonny Sep 04 '13 at 01:42
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.

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))
FelixEnescu
  • 4,664
  • 2
  • 33
  • 34
Xuan
  • 5,255
  • 1
  • 34
  • 30
13

python itself has a json module, which will make sure that your JSON is properly formatted, handwritten JSON is more prone to get errors.

import json
self.response.headers['Content-Type'] = 'application/json'   
json.dump({"success":somevar,"payload":someothervar},self.response.out)
bigblind
  • 12,539
  • 14
  • 68
  • 123
  • 1
    i might be wrong but i doubt this actually works this way. why would you pass `self.response.out` to the `dump` function as an argument? – aschmid00 Sep 30 '12 at 21:23
  • 12
    It does work that way. self.response.out is a stream and dump() takes a stream as its second argument. (Maybe you're confused by the difference between dump() and dumps()?) – Guido van Rossum Oct 01 '12 at 01:18
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)
nguyên
  • 5,156
  • 5
  • 43
  • 45
1
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...

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

or

return jsonify({ 'arg1': 'val1', 'arg2': 'val2' })
Travis Vitek
  • 216
  • 1
  • 6