How to properly output JSON with app engine Python webapp2?

Ryan picture Ryan · Sep 30, 2012 · Viewed 26.6k times · Source

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?

Answer

Lipis picture Lipis · Sep 30, 2012

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