问题
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