0

I am trying to return a python dictionary to the view with AJAX and reading from a JSON file, but so far I am only returning [object Object],[object Object]...

and if I inspect the network traffic, I can indeed see the correct data.

So here is how my code looks like. I have a class and a method which based on the selected ID (request argument method), will print specific data. Its getting the data from a python discretionary. the problem is not here, have already just tested it. But just in case I will link it.

# method to create the directionary - just in case #

def getCourselist_byClass(self, classid):
        """
        Getting the courselist by the class id, joining the two tables. 
        Will only get data if both of them exist in their main tables.
        Returning as a list.
        """
        connection = db.session.connection()
        querylist = []
        raw_sql = text("""
           SELECT
                course.course_id,
                course.course_name
            FROM
                course
            WHERE
                EXISTS(
                    SELECT 1
                    FROM
                        class_course_identifier
                    WHERE
                        course.course_id = class_course_identifier.course_id
                    AND EXISTS(
                        SELECT 1
                        FROM
                            class
                        WHERE
                            class_course_identifier.class_id = class.class_id
                        AND class.class_id = :classid
                    )
                )""")
        query = connection.engine.execute(raw_sql, {'classid': classid})
        for column in query:
            dict = {
                'course_id'     : column['course_id'],
                'course_name'   : column['course_name']
            }
            querylist.append(dict)

        return querylist

my jsonify route method

@main.route('/task/create_test')
def get_courselist():
    #objects
    course = CourseClass()
    class_id = request.args.get('a',  type=int)    
    #methods
    results = course.getCourselist_byClass(class_id)
    return jsonify(result=results)

HTML

and here is how the input field and where it should link the data looks like.

<input type="text" size="5" name="a">
        <span id="result">?</span>
        <p><a href="javascript:void();" id="link">click me</a>

and then I am calling it like this

<script type=text/javascript>
    $(function() {
        $('a#link').bind('click', function() {
          $.getJSON("{{ url_for('main.get_courselist') }}", {
            a: $('input[name="a"]').val()
          }, function(data) {
            $("#result").text(data.result);
          });
          return false;
        });
    });
  </script>

but every time I enter a id number in the field, i am getting the correct data. but it is not formatted correctly. It is instead printing it like [object Object]

source, followed this guide as inspiration: flask ajax example

2 Answers 2

1

The data return by your server is like: {result: [{course_id: 'xxx', course_name: 'xxx'}]}, in which data.result is a JS Array.

when you set it to $("#result").text(), JS convert a array to string, so the result is [object Object].

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

courseStr = data.result.map(function(course) {return course.course_id + '-' +   course.course_name; }).join(',');
$("#result").text(courseStr);
Sign up to request clarification or add additional context in comments.

Comments

1

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:

return dumps(results)

5 Comments

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]
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
thanks a lot @rchang , I need to read more about how to serialize! I am still new to programming and python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.