Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly output JSON with app engine Python webapp2?

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?

like image 999
Ryan Avatar asked Sep 30 '12 20:09

Ryan


3 Answers

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))
like image 59
Lipis Avatar answered Nov 07 '22 11:11

Lipis


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))
like image 31
Xuan Avatar answered Nov 07 '22 11:11

Xuan


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)
like image 13
bigblind Avatar answered Nov 07 '22 12:11

bigblind