Rectangle 27 0

python Return JSON object to View with Flask and Ajax?


$("#result").text()
[object Object]
courseStr = data.result.map(function(course) {return course.course_id + '-' +   course.course_name; }).join(',');
$("#result").text(courseStr);
data.result
{result: [{course_id: 'xxx', course_name: 'xxx'}]}

That was exactly what I needed thank you!

You should iterate over the array to construct a string, then set the string in DOM, like:

Note
Rectangle 27 0

python Return JSON object to View with Flask and Ajax?


return dumps(results)

As an alternative, maybe try Python's built-in json module. It too provides a dumps method that accepts an object. I know I've successfully used this before to serialize a list of dictionaries (although that was not on a Flask project). Docs at docs.python.org/2/library/json.html for Python 2.7 and docs.python.org/3.3/library/json.html for Python 3.3

Hello, when I try dumps. I am not getting anything to the DOM, but I can see under "network", that it is getting the JSON object.

In the .getJSON callback, I think you're still looking for the result attribute in the inbound JSON (back from when you were using jsonify). Maybe try $("#result").text(data); instead?

Thanks @rchang, but it seems that I am getting the same error as with jsonify. Still getting [object Object]

The API description for flask.json.jsonify indicates it's expecting keyword parameters. What you actually want to do seems to be serialize a list object containing dictionaries, have you tried flask.json.dumps instead? Assuming you've got the dumps symbol imported, instead of your jsonify call you can try:

Note
Rectangle 27 0

python Return JSON object to View with Flask and Ajax?


return dumps(results)

As an alternative, maybe try Python's built-in json module. It too provides a dumps method that accepts an object. I know I've successfully used this before to serialize a list of dictionaries (although that was not on a Flask project). Docs at docs.python.org/2/library/json.html for Python 2.7 and docs.python.org/3.3/library/json.html for Python 3.3

Hello, when I try dumps. I am not getting anything to the DOM, but I can see under "network", that it is getting the JSON object.

In the .getJSON callback, I think you're still looking for the result attribute in the inbound JSON (back from when you were using jsonify). Maybe try $("#result").text(data); instead?

Thanks @rchang, but it seems that I am getting the same error as with jsonify. Still getting [object Object]

The API description for flask.json.jsonify indicates it's expecting keyword parameters. What you actually want to do seems to be serialize a list object containing dictionaries, have you tried flask.json.dumps instead? Assuming you've got the dumps symbol imported, instead of your jsonify call you can try:

Note