Skip to content Skip to sidebar Skip to footer

Return A List As Json From Web2py

Is there any way to return a list as a JSON list from web2py? when I hit my route ending in .json, web2py converts dictionaries into valid JSON. If the return value is a list howev

Solution 1:

If you want to return a JSON response, your function must either return JSON or trigger the execution of a view that will produce JSON. In web2py, a view will only be executed if a controller function returns a dictionary, so your function will not result in a view being executed (as it does not return a dictionary). If your function did return a dictionary, you would still need to have a .json view defined, or explicitly enable the generic.json view via response.generic_patterns (though generic.json would not actually be suitable in your case, as it converts the entire dictionary returned by the function to JSON -- so you could not use it to output only a list).

The simplest solution is just to output JSON directly:

import json
    ...
    return json.dumps(['test', 'test'])

or even more simply:

return response.json(['test', 'test'])

Solution 2:

registering a json service with the @service.json decorator and calling it with `app/controller/call/json/method' gave me the behaviour I expected:

deff():
    return ["test1", "test2"]

defcall():
    return service()

The response body is

["test1", "test2"]

with content-type set to json

Post a Comment for "Return A List As Json From Web2py"