CherryPy How to respond with JSON? CherryPy How to respond with JSON? python python

CherryPy How to respond with JSON?


Since CherryPy 3.2 there are tools to accept/return JSON:

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

Using json_out serializes the output and sets the appropriate Content-Type header for you.

Similarly decorating with @cherrypy.tools.json_in() can automatically accept/decode JSON post requests.


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)