WoJ WoJ - 20 days ago 5
JSON Question

Why doesn't bottle return lists?

(Note: this is a duplicate, I voted to close it as such but it may never happen so I prominently place the info here as I never know if the yellow informational banner about a possible duplicate is seen by everyone or just me)

I would like to return a JSON representation of a list using

bottle
:

import bottle

def ret_dict():
return {
"who": {"name": "John"}
}

def ret_list():
return [
{"name": "John"}
]

app = bottle.Bottle()
app.route('/dict', 'GET', ret_dict)
app.route('/list', 'GET', ret_list)
app.run()


Calling
http://127.0.0.1:8080/dict
returns
{"who": {"name": "John"}}
and
Content-Type
is set to
application/json
. This is OK.

Calling
http://127.0.0.1:8080/list
returns a
500
:


Error: 500 Internal Server Error Sorry, the requested URL

'http://127.0.0.1:8080/list' caused an error:

Unsupported response type: < class 'dict' >


There is no error nor traceback on the Python console.

At the same time a list can be serialized to JSON:

>>> import json
>>> json.dumps([{"name": "John"}])
'[{"name": "John"}]'


Why does
bottle
raises an error when trying to return a
list
?
(and happily returning a
dict
)

Answer

Bottle's JSON plugin can only return objects of dict type - not list. There are vulnerabilities related to returning JSON arrays - see this post about JSON hijacking.

As a workaround you may wrap the list object under dict with some key say, data as:

def ret_list():
    my_data = [
        {"name": "John"}
    ]
    return {'data': my_data}

Also read Vinay's answer to "How do I return a JSON array with Bottle?".