return a list as JSON from web2py

强颜欢笑 提交于 2019-12-11 05:47:18

问题


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 however, it behaves unexpectedly

return ["test", "test"]

displays

testtest

and

return [dict(test="test"), dict(test="test")]

breaks it completely (chrome complains with ERR_INVALID_CHUNKED_ENCODING). The expect behaviour is obviously the following valid JSON strings respectively:

["test", "test"]

and

[{"test":"test"}, {"test":"test"}]

回答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'])



回答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:

def f():
    return ["test1", "test2"]

def call():
    return service()

The response body is

["test1", "test2"]

with content-type set to json



来源:https://stackoverflow.com/questions/40430152/return-a-list-as-json-from-web2py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!