views:

99

answers:

2
+2  A: 

Not sure what you mean by "without using tools" -- Python is "a tool", right?

With just Python and its standard library (2.6 or better), add at the top of your module

import json

and change the return statement to

return json.dumps(message)
Alex Martelli
In Python 2.5, you can use the [simplejson](http://pypi.python.org/pypi/simplejson/) package.
detly
Actually, what I meant by saying "without tools" was without using decorators. I'm still getting used to python's idiosyncrasies. Yes, I have seen simplejson used, but I want to be able to do it using the base libraries first.
Sean Ochoa
@Sean, `simplejson` is just the older version of `json`, from before the latter was incorporated into the Python standard library. IOW, `json` is not any more "base" than `simplejson`, it's just a "packaging" decision by the PSF (specifically by the core developers of Python itself and the standard library that goes with it).
Alex Martelli
@Alex: "Tool" is CherryPy jargon for "plugin". There's a whole subsystem for using them and making your own: http://docs.cherrypy.org/dev/intro/concepts/tools.html
fumanchu
@fumanchu, tx for the translation!-)
Alex Martelli
+1  A: 

Note that in CherryPy 3.2 (almost done!) there will be a pair of JSON tools to make the above even easier:

@cherrypy.expose
@tools.json_out()
def monkey(self, **kwargs):
    return {"message": "Hello World!"}

json_out encodes the output and sets the header for you.

fumanchu
Thanks for this. In reading Alex's post above and doing some testing on my own, I realize that your suggestion is more succinct, explicit, and readable than using JSON.dumps().
Sean Ochoa