Data exchange between Flask and Javascript

Issue

I wrote a simple application in Python Flask. There is a page, part of which should be updated after a certain interval (for example, 1 second). I have no idea how to implement this on Flask, so I decided to use JavaScript (I’m practically not familiar with this language). The script accesses the Flask server at a specific URL every second and receives data in JSON format. In Python, the handler for this URL sends a response using the jsonify() function. The object being sent is an array of dictionaries in Python – [{key: value,...}, {key: value,...},...]. In JavaScript, I get (probably) an array of objects – [object Object], [object Object]. My question is how do I get a similar object in JS, as in Python, in order to correctly extract the information.
In Python:

[{'sender': '10.0.0.10:3000', 'recipient': ['10.0.0.10:2000'], 'amount': 1, 'message': 'hi'}, 
{'sender': '10.0.0.10:3000', 'recipient': ['10.0.0.10:2000'], 'amount': 1, 'message': 'hello'}]

In JS:

[object Object], [object Object]

URL handler, messages – an array of dictionaries:

@app.route('/consensus', methods=['GET'])
def consensus():
    messages = blockchain.resolve_conflicts()
    return jsonify(messages=messages)

JS script, the html page has a block with the ID #message

    setInterval(function () {
                $SCRIPT_ROOT = {{ request.script_root|tojson|safe }}
                $.getJSON($SCRIPT_ROOT+"/consensus",
                    function(data) {
                        $("#messages").text(data.messages)
                    });
            }
    , 10000)

Solution

Try this to see what the objects are composed of:

$("#messages").text(JSON.stringify(data.messages))

Then you need to learn about accessing object properties. What is happening is your object is being converted to a string, which for any JS object it’s string value is object Object by default.

If your object is like this: x = {name: 'Tom'} then if you print the object (x) it prints object Object – but if you print x.name it will print tom.

In other words, you need to format your string and not just print the object’s string value.

There are lots of examples of how to do this, here are a few: https://www.w3schools.com/js/js_object_display.asp

Answered By – mikeb

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published